query
query

Reputation: 21

Unambigous behaviour during print in Ruby

The print statement given below executes correctly when I remove the parentheses and produces an error syntax error, unexpected ',', expecting ')' when parentheses are kept. Any help would be appreciated since I am new to Ruby

print "Enter name: "
name=gets
puts name
puts "Enter first number"
num1=gets
puts "Enter Second number"
num2=gets
result=Integer(num1)+Integer(num2)
print ("The addition of "+num1.chomp+" and " + num2.chomp+ " is ",result)

Upvotes: 0

Views: 73

Answers (3)

Hasmukh Rathod
Hasmukh Rathod

Reputation: 1118

print "Enter name: "
name=gets.strip   ##strip method removes unnecessary spaces from start & End
puts "Enter first number"
num1=gets.strip.to_i   ##convert string number into Int
puts "Enter Second number"
num2=gets.strip.to_i
result=num1+num2
print "The addition: #{num1} + #{num2} = #{result}"   ##String interpolation.

Upvotes: 0

Eric Duminil
Eric Duminil

Reputation: 54263

Do you have a Python background? This code looks like Python written in Ruby ;)

print 'Enter first number: '
num1 = gets.to_i
print 'Enter Second number: '
num2 = gets.to_i
puts format('The addition of %d and %d is %d', num1, num2, num1 + num2)

String#to_i is more often used than Integer(). Also, both Integer() and to_i ignore newlines, so you don't need to call chomp.

Kernel#format is a good and fast way to integrate variables in a string. It uses the same format as C/Python/Java/...

Upvotes: 2

Frank Schmitt
Frank Schmitt

Reputation: 30815

There are several ways to achieve what you want:

  • get rid of the space between print and (

    print("The addition of " + num1.chomp + " and " + num2.chomp + " is ", result)

  • use + to concatenate the strings; this will require you to use to_s to convert the numeric value result into a string:

    print("The addition of " + num1.chomp + " and " + num2.chomp + " is " + result.to_s)

  • use string interpolation:

    print("The addition of #{num1.chomp} and #{num2.chomp} is #{result}")

Upvotes: 2

Related Questions