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.
03 Answers
%i[ ] # Non-interpolated Array of symbols, separated by whitespace %I[ ] # Interpolated Array of symbols, separated by whitespace The second link from my search results
Examples in IRB:
%i[ test ] # => [:test] str = "other" %I[ test_#{str} ] # => [:test_other] 4It 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]
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