What does %i or %I do in Ruby?
Ruby on-RailsRubyRuby on-Rails Problem Overview
What's the meaning of %i
or %I
in ruby?
I searched Google for
"%i or %I" ruby
but I didn't find anything relevant to Ruby.
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
%i[ ] # Non-interpolated Array of symbols, separated by whitespace
%I[ ] # Interpolated Array of symbols, separated by whitespace
The second link from my search results http://ruby.zigzo.com/2014/08/21/rubys-notation/
Examples in IRB:
%i[ test ]
# => [:test]
str = "other"
%I[ test_#{str} ]
# => [:test_other]
Solution 2 - Ruby on-Rails
It can be hard to find the official Ruby documentation ([it's here][1]). At the time of writing the current version is 2.5.1, and the documentation for the %i construct is found in the documentation for [Ruby's literals.][2]
There are some surprising (to me at least!) variants of Ruby's % construct. There are the often used %i %q %r %s %w %x
forms, each with an uppercase version to enable interpolation. (see the [Ruby literals docs][2] for explanations.
But you can use many types of delimiters, not just []
. You can use any kind of bracket () {} [] <>
, and you can use (quoting from the ruby docs) "most other non-alphanumeric characters for percent string delimiters such as “%”, “|”, “^”, etc."
So %i% bish bash bosh %
works the same as %i[bish bash bosh]
[1]: https://ruby-doc.org/ "it's here" [2]: https://ruby-doc.org/core-2.5.1/doc/syntax/literals_rdoc.html
Solution 3 - Ruby on-Rails
It's like %w
and %W
which work similar to '
and "
:
x = :test
# %w won't interpolate #{...} style strings, leaving as literal
%w[ #{x} x ]
# => ["\#{x}", "x"]
# %w will interpolate #{...} style strings, converting to string
%W[ #{x} x ]
# => [ "test", "x"]
Now the same thing with %i
and %I
:
# %i won't interpolate #{...} style strings, leaving as literal, symbolized
%i[ #{x} x ]
# => [:"\#{x}", :x ]
# %w will interpolate #{...} style strings, converting to symbols
%I[ #{x} x ]
# => [ :test, :x ]