如何在单个项目上运行每个循环?
问题描述:
我拉着一个特定对象的所有关联对象,并对其做一个each_with_index
。如何在单个项目上运行每个循环?
即。 subscription.transactions.each_with_index
但是,当只有一个transaction
(因此它不是一个数组),我得到一个undefined method 'each'
错误。
我该如何解决这个问题,基本上只运行一次each
?
答
你可以做
Array(subscription.transactions).each_with_index
答
你也可以做到这一点
[subscription.transactions].flatten.each_with_index