In Ruby, you can apply a map function to every element of an array:

@files.map { |f| f.read) }

For which there is the syntactic sugar:

@files.map(&:read)

Is there any equivalent for

@files.map { |f| read(f) } 

That is terser, similar to the above?

  • 1
    It is not syntax sugar. It is just how Symbol#to_proc works. – sawa Dec 12 '12 at 8:12
up vote 16 down vote accepted

You can do this

@files.map(&method(:read))

But be aware though about performance.

  • 3
    To me, it isn't shorter at all. Just more complicated and less performant :) – Sergio Tulentsev Dec 12 '12 at 7:46
  • @SergioTulentsev Why would it be more complicated ? – oldergod Dec 12 '12 at 7:54
  • It uses more chars, for one thing :) – Sergio Tulentsev Dec 12 '12 at 7:57
  • I agree it's more complicated, but I'm accepting since it's the logical equivalent of the first idiom. – user2398029 Dec 12 '12 at 8:08

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.