Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbers vs string/expressions vs values

Tags:

ruby

When I type the following:

print "2+2 is equal to" +2+2

I get an error message saying I can't convert a number into a string, but when I type:

print "2+2 is equal to", 2+2

it's accepting it and displays:

2+2 is equal to4

What's the difference between the two? It's not making logical sense to me. Could someone please explain it?

like image 687
khurrem Avatar asked Dec 21 '25 23:12

khurrem


1 Answers

print "2+2 is equal to" + 2 + 2

Here you're trying to add a number to a string. This operation doesn't make sense. It's like adding an apple to a cat. The addition fails, but if it were to succeed, then print would print the result.

print "2+2 is equal to", 2 + 2 

Here you're telling the print command to print this string and also result of summing these two numbers. it knows how to print strings and how to print numbers. Strings and numbers don't have to be mixed together in this case, they are handled separately. That's why this operation succeeds.

You can make the first operation work too. For this, you must be explicit that you want this number as a string, so that both addition operands are strings and can be actually added together.

print "2+2 is equal to" + (2 + 2).to_s

or

print "2+2 is equal to #{2 + 2}" # this is called string interpolation

Some languages try to be friendly and, if you're adding a number to a string, will stringify the number for you. Results can be... surprising.

Javascript:

"2 + 2 equals to " + 2 + 2 
# => "2 + 2 equals to 22"

"2 + 2 equals to " + (2 + 2) 
# => "2 + 2 equals to 4"

It's good that ruby doesn't do this kind of tricks :)

like image 157
Sergio Tulentsev Avatar answered Dec 24 '25 09:12

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!