108

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.

0

3 Answers 3

155
%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] 
4
  • 2
    aka the % notation
    – anothermh
    Oct 31, 2017 at 16:08
  • 1
    This is correct. I don't recommend using %I however. Oct 31, 2017 at 16:37
  • 6
    @MarkThomas Why don't you recommend %I would you elaborate? Jul 28, 2019 at 16:27
  • 1
    @ArupRakshit My guess is that it's ugly and can be much less clear than using a more obvious String interpolation. Nov 5, 2020 at 17:08
32

It can be hard to find the official Ruby documentation (it's here). 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.

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 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
17

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 ]
2
  • 1
    This answers the question more clearly. The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces. Thanks a lot for your answer.
    – Vishal K
    Apr 30, 2019 at 11:00
  • 2
    @VishalKanaujia While symbols are often used as hash keys, that's not their only purpose. In Ruby a hash key can be literally anything, and symbols can be used in many other circumstances.
    – tadman
    Apr 30, 2019 at 15:54

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.