⇐ Previous | Next ⇒

Create an Array of Symbols with %i{} in Ruby 2

Post created 2013-12-05 07:55 by Gabe Koss.

Ruby has long has many nice pieces of syntactic sugar but one of my favorites is the new %i{} Array constructor.

There has long been the %w{} operator to create an array of strings with minimal characters. This works as follows:

%w{ this is an array }
# => ["this", "is", "an", "array"] 

All too often I end up doing something like this:

%w{ this is an array }.map(&:to_sym)
# => [:this, :is, :an, :array] 

In Ruby 2 this can be accomplished with:

%i{ these are symbols }
# => [:these, :are, :symbols] 

When I realized it worked this way:

It was a good day

comments powered by Disqus