Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute 'map' in Ruby without using blocks?

Tags:

ruby

I know I can do this in Ruby:

  ['a', 'b'].map do |s| s.to_sym end

and get this:

  [:a, :b]

I'm looking for a more concise way to do it, without using a block. Unfortunately, this doesn't work:

  ['a', 'b'].map #to_sym

Can I do better than with the initial code?

like image 756
Joshua Chia Avatar asked Sep 05 '11 16:09

Joshua Chia


2 Answers

Read a bit about Symbol#to_proc:

['a', 'b'].map(&:to_sym)
# or
['a', 'b'].map &:to_sym
# Either will result in [:a, :b]

This works if you're using Ruby 1.8.7 or higher, or if you're using Rails - ActiveSupport will add this functionality for you.

like image 83
PreciousBodilyFluids Avatar answered Oct 07 '22 21:10

PreciousBodilyFluids


['a', 'b'].map(&:to_sym) is shorter

like image 44
lucapette Avatar answered Oct 07 '22 23:10

lucapette