Home > other >  print i Vs. print "#{i} in Ruby? Is there a difference without adding it to a string?
print i Vs. print "#{i} in Ruby? Is there a difference without adding it to a string?

Time:09-12

I am a little confused between both of the below in codeacademy examples and want to understand well & know:

  • What is the difference between both?
  • Is there a time I should use one instead the other?

For Example:


array = [1,2,3,4,5]

array.each do |x|
  x  = 10
  print x     #thats what I mean x only not "{x}" as below
end

array = [1,2,3,4,5]

array.each do |x|
  x  = 10
  print "#{x}"
end

Is that because they consider to add it as variable with string??

CodePudding user response:

print x and print "#{x}" are the same

Arguments of print that aren't strings will be converted by calling their to_s method

It means that print x is the same as print x.to_s, but x.to_s is the same as "#{x}" (to_s is applied to the interpolation result)

Due to brevity, it is usually customary to use without interpolation. But if you wish to concatenate some other object, use interpolation (i.g. print "#{x}#{y}")

CodePudding user response:

What is the difference between x and "#{x}"?

print x

The x returns the value in whatever type it is. If it is an integer, it will return an integer.

In your first example, it IS an integer So, the value returned by x is an Integer type value.

To check what type it is, you can do:

print x.class # returns the class which the value belongs to. 

print "#{x}"

The x returned here, is first converted into a string, no matter whatever type it is. If it is an integer, it will still return the value in string type. This is called String Interpolation. You can read more about it here.

In your other example, x IS an integer. But at the time of printing it, the value "#{x}" is returned as a string.

To check what type it is, you can do:

print "#{x}".class # returns the class which the value belongs to. 

Is there a time I should use one instead the other?

Is that because they consider to add it as variable with string?? Yes, that is one of the reasons we want String Interpolation.

  •  Tags:  
  • ruby
  • Related