我如何将索引合并到变量名中以便我可以访问不同的组对象?
这是我的 db/seeds.rb 文件:
u = User.create( email: "yeah@foo.com", password: "yeah", password_confirmation: "yeah")
groups_list = ["Math Club", "Science Class", "Economics Class"]
groups_list.each_with_index do |name, index|
"g#{index}" = u.groups.create(name: name)
end
最佳答案
当您开始需要动态定义的局部变量时,您会感觉到代码的味道,并且您知道应该重新考虑您正在做的事情。
看起来您最好使用 map
调用,将 groups_list
从字符串数组转换为 Group
数组属于 u
的对象:
groups_list.map { |name| u.groups.create name: name }
#=> [<Group name="Math Club">, …]
然后您可以遍历这些组或将它们作为数组传递给另一个方法,不涉及任何技巧。
关于ruby-on-rails - 使用 each_with_index 循环时如何将索引合并到变量名中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16764468/