【问题标题】:How do I construct an object in ruby Array Map?如何在 ruby​​ Array Map 中构造对象?
【发布时间】: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


【解决方案1】:

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

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

被传递的块是一个 Proc 并且 Procs 不允许显式返回调用。更多信息请参考Why does explicit return make a difference in a Proc?

【讨论】:

  • 赞成,但 IMO 你应该解释为什么return 不起作用。
  • 我相信你可以使用break return_val从块中显式返回值。普通的return 从整个方法返回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2019-09-12
  • 2023-03-13
  • 2011-10-17
  • 1970-01-01
  • 2023-02-06
相关资源
最近更新 更多