Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between print i and print "#{i}" in Ruby?

Tags:

ruby

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

like image 282
Saoud ElTelawy Avatar asked Jan 21 '26 20:01

Saoud ElTelawy


1 Answers

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}")

like image 50
mechnicov Avatar answered Jan 23 '26 09:01

mechnicov