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

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

1111. appearing after print sequence - php -