Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using %i and %I symbol array literal

Reading through a list of Rails questions, I'm having trouble finding what the %i does in relation to a symbol array. Does this mean anything to anyone?

like image 941
Mark Avatar asked Oct 01 '16 05:10

Mark


People also ask

What is W [] in Ruby?

Save this answer. Show activity on this post. %w(foo bar) is a shortcut for ["foo", "bar"] . Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

What does %I mean in Ruby?

The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.

What are literals in Ruby?

A literal is a special syntax in the Ruby language that creates an object of a specific type. For example, 23 is a literal that creates a ​Fixnum object. As for String literals, there are several forms.


2 Answers

Lowercase %i stands for

Non-interpolated Array of symbols, separated by whitespace (after Ruby 2.0)

In addition, uppercase %I means

Interpolated Array of symbols, separated by whitespace (after Ruby 2.0)

Example of difference regarding interpolation:

2.4.2 :001 > a = 1 2.4.2 :002 > %i{one two #{a}+three} # Interpolation is ignored  => [:one, :two, :"\#{a}+three"] 2.4.2 :003 > %I{one two #{a}+three} # Interpolation works  => [:one, :two, :"1+three"] 

Have a look at here for further information.

like image 87
Andres Avatar answered Oct 05 '22 19:10

Andres


I'm having trouble finding what the %i does in relation to a symbol array.

It is an array literal for an array of symbols. It does the same thing in relation to symbol arrays as ' does to strings.

like image 29
Jörg W Mittag Avatar answered Oct 05 '22 17:10

Jörg W Mittag