%i and %I in Ruby
Sometimes you may need to retrieve a variable’s value inside an array. This is mainly required when the variable’s value is related to the array you’re working on.
You can easily do that in Ruby by using the %i
or %I
.
This article will discuss how we can use the %i
or %I
in Ruby, along with their differences. Also, we are going to take a look at an example to make the topic easier.
Use the %i
in Ruby
In our example below, we will demonstrate the use of %i
in Ruby. Let’s take a look at our below example.
a = :test
puts %i[#{a} x]
If you look at the result, you will find that the %i
won’t resolve a
and will provide you with the below output.
#{x}
x
Use the %I
in Ruby
In our example below, we will demonstrate the use of %I
in Ruby. Let’s take a look at our below example.
a = :test
puts %I[#{a} x]
Now, if you look at the result, you will find that the %I
resolved a
and replaced it with its value. After running the above example, you will get output like the one below.
test
x
Please note that:
%i[ ]
- Non-interpolated array; it will never resolve symbols.%I[ ]
- Interpolated array; it will resolve symbols.
Please note that all the code this article shares is written in Ruby.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn