Create array of symbols

Ruby

Ruby Problem Overview


Is there a cleaner way to do something like this?

%w[address city state postal country].map(&:to_sym) 
#=> [:address, :city, :state, :postal, :country]

I would have figured %s would have done what I wanted, but it doesn't. It just takes everything between the brackets and makes one big symbol out of it.

Just a minor annoyance.

Ruby Solutions


Solution 1 - Ruby

The original answer was written back in September '11, but, starting from Ruby 2.0, there is a shorter way to create an array of symbols! This literal:

%i[address city state postal country]

will do exactly what you want.

Solution 2 - Ruby

With a risk of becoming too literal, I think the cleanest way to construct an array of symbols is using an array of symbols.

fields = [:address, :city, :state, :postal, :country]

Can't think of anything more concise than that.

Solution 3 - Ruby

%i[ ] Non-interpolated Array of symbols, separated by whitespace (after Ruby 2.0)

%I[ ] Interpolated Array of symbols, separated by whitespace (after Ruby 2.0)

%i[address city state postal country]

the cleanest way to do this is:

%w[address city state postal country].map(&:to_sym)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrewView Question on Stackoverflow
Solution 1 - RubyJoost BaaijView Answer on Stackoverflow
Solution 2 - RubyJoost BaaijView Answer on Stackoverflow
Solution 3 - RubyaskrynnikovView Answer on Stackoverflow