假设:
class Thing
def initialize(object)
@object = object
end
end
items = [1,2,3]
我想知道一种更优雅的方式将每件商品转换为Thing而不是:
items.map{ |item| Thing.new item }
# => [<Thing @object=1>, <Thing @object=2>, <Thing @object=3>]
答案 0 :(得分:6)
您可以使用一元前缀&
运算符:
items.map(&Thing.method(:new))
I have suggested that Class
es should behave as Factory Functions,允许你这样写:
items.map(&Thing)
但是,对该提案似乎没什么兴趣。你可以自己修补它,但实现起来很简单:
class Class
def to_proc
method(:new).to_proc
end
end
答案 1 :(得分:3)
我认为你的榜样非常好。但也许你喜欢这样的东西:
# in item.rb
def to_thing
Thing.new(self)
end
这将允许你写:
items.map(&:to_thing)