ruby Elegantly wrap an array of items each into an object -


given:

class thing   def initialize(object)     @object = object      end end  items = [1,2,3] 

i'd know of more elegant way convert each item thing this:

items.map{ |item| thing.new item } # => [<thing @object=1>, <thing @object=2>, <thing @object=3>] 

you can use unary prefix & operator:

items.map(&thing.method(:new)) 

i have suggested classes should behave factory functions, allow write this:

items.map(&thing) 

however, there doesn't seem interest in proposal. can monkey-patch yourself, though, implementation trivial:

class class   def to_proc     method(:new).to_proc   end end 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -