11

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?

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It works on 1.8.7 too. 1.8.7 (main):0 > RUBY_DESCRIPTION => "ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux]" 1.8.7 (main):0 > ['a', 'b'].map(&:to_sym) => [:a, :b]
lucapette: Yeah, I did a quick edit to add/fix some information.
Yep I saw it. You know, with all this implementations out there I'm having issues with remembering stuff. When I read your reply I went to check I remembered it well ;)
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.