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
我相信必须有更好的方法来做到这一点?