【发布时间】:2013-03-09 08:26:26
【问题描述】:
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
我相信一定有更好的方法来做到这一点?
【问题讨论】:
-
您的底部示例非常更易于阅读和理解。
标签: ruby performance coding-style