class TestClass
attr_accessor :name, :id
end
values = ["test1", "test2"]
mapped_values = values.map{|value|
test_class = TestClass.new
test_class.name = value
test_class.id = #some random number
return test_class
}
puts mapped_values
显然这不起作用,它只会返回第一个值,而不是整个新构造的列表。 我有这个测试脚本,我想要实现的是它从 Array.map 操作返回包含值名称和 id 的 TestClass 列表。我只是想找到在 Ruby 中做到这一点的最佳方法。
我可以做这样的事情
tests = []
values.each do |value|
test_class = TestClass.new
test_class.name = value
test_class.id = #some random number
tests << test_class
end
我相信一定有更好的方法来做到这一点?
最佳答案
如果您想使用 map ,请删除返回调用。
mapped_values = values.map{|value|
test_class = TestClass.new
test_class.name = value
test_class.id = #some random number
test_class
}
传递的 block 是一个 Proc,而 Procs 不允许显式返回调用。请引用Why does explicit return make a difference in a Proc?了解更多信息
关于ruby - 如何在 ruby Array Map 中构造对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15520231/