Create array of symbols

%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)


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.


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.

Tags:

Ruby