2
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

我相信必须有更好的方法来做到这一点?

4

1 回答 1

3

如果要使用地图,请删除返回调用。

mapped_values = values.map{|value|
  test_class = TestClass.new
  test_class.name = value
  test_class.id = #some random number
  test_class
}

被传递的块是一个 Proc 并且 Procs 不允许显式返回调用。请参阅为什么显式返回会在 Proc 中产生影响?了解更多信息

于 2013-03-20T10:11:51.493 回答