在使用each_with_index进行循环时,如何将索引合并到变量名中?



如何将索引合并到变量名中,以便访问不同的组对象?

这是我的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从字符串数组转换为属于uGroup对象数组:

groups_list.map { |name| u.groups.create name: name }
#=> [<Group name="Math Club">, …]

然后可以遍历这些组,或者将它们作为数组传递给另一个方法,不需要任何技巧。

最新更新