Unambigous behaviour during print in Ruby - 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)

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

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/...

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.

Related

Why can't I print strings with integers?

num1 = 2
num2 = 4
op = num1 + num2
puts "enter a number would like to multiply with 6"
num3 = gets.to_i * op
print ("its " + num3 + " man")
Why doesnt this work? If i have it as 'print num3' alone itll work. What is going on?
The answers to this question, Concatenating string with number in ruby, outline two ways you can do it via either:
string interpolation
or, using .to_s to change the number to a string when constructing the result string
Using .to_s you can do this:
print ("its " + num3.to_s + " man")
Although using string interpolation may be a better approach.
Described here:
https://ruby-doc.org/core-2.5.0/doc/syntax/literals_rdoc.html
You can't concat Fixnum and string.
Please do it like this.
print ("its #{num3} man")
If i have it as print num3 alone it'll work. What is going on?
print can indeed print arbitrary objects using their to_s methods, even multiple objects.
But in order to do so, you have to pass them as separate arguments:
num = 42
print('its ', num, ' man')
# its 42 man
However, it's more idiomatic to use string interpolation:
print("its #{num} man")
# its 42 man
or printf which takes a template string: (%d means decimal number)
printf('its %d man', num)
# its 42 man
Note that none of the above will print a newline. If you want one, you have to append \n yourself, or use puts which adds it automatically.

String can't be coerced into Fixnum (TypeError)

I wrote the basic codes below
puts ' Hi there , what is your favorite number ? '
number = gets.chomp
puts number + ' is beautiful '
puts 1 + number.to_i + 'is way better'
But when I run it,I get the error "String can't be coerced into Fixnum (TypeError)". How do I correct this error please?
You cannot add a String to a number. You can add a number to a String, since it is coerced to a String:
'1' + 1
# => "11"
1 + 1
# => 2
1 + '1'
# TypeError!
Since I suspect you want to show the result of adding 1 to your number, you should explicitly cast it to string:
puts (1 + number.to_i).to_s + ' is way better'
or, use string interpolation:
puts "#{1 + number.to_i} is way better"
String can't be coerced into Integer usually happens, when you try to add a string to a number. since you want to add 1 to your number and concatenate it with a string "is way better". you have to explicitly cast the result you got from adding 1 to your number to a string and concatenate it with your string "is way better".
you can update your code to this:
puts (1 + number.to_i).to_s + " " + 'is way better'
Assuming that the numbers are natural numbers:
number = gets.chomp
puts "#{number} is beautiful ", "#{number.succ} is way better"
You might find the results of entering 'xyz' as an input surprising.
This discussion for determining if your input string is a number may be helpful.

Beginner on Ruby making a calculator

this is my first entry to StackOverflow and I'm a newbie coder.
So I'm making a simple addition calc and I added commas in the last 2 lines to print out integers ...
What am I missing? The error says
C:/Ruby193/rubystuff/ex1.rb:13: syntax error, unexpected ',' print
("The result of the addition is " +,result)
I thought this was the right thing to do ... i must have missed something simple.
print ("Please enter your name: ")
name = gets
puts ("Hello, " + name)
print ("Enter a number to add: ")
num1 = gets
print ("Enter a second number to add: ")
num2 = gets
result = Integer(num1) + Integer(num2)
print result
print ("The result of the addition is ",result)
print ("So the result of adding " + num1.chomp + " plus " + num2.chomp + " equals: ",result)
Ruby has string interpolation and I think most would argue that's the most idiomatic way of doing things. RubyMonk does a great job explaining it here
by changing the 'print' call to the puts method you can do:
puts "The result of the additions is #{result}"
There are two ways to pass arguments to a method:
in parentheses directly after the method name
without parentheses with whitespace after the method name
You have white space after the method, ergo you are using option #2 and are passing a single argument ("The result of the addition is ",result) to the method, but ("The result of the addition is ",result) is not legal syntax.

Why doesn't puts() print in a single line?

This is a piece of code:
def add(a, b)
a + b;
end
print "Tell number 1 : "
number1 = gets.to_f
print "and number 2 : "
number2 = gets.to_f
puts "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
When I run it, my results are spread over several lines:
C:\Users\Filip>ruby ext1.rb
Tell number 1 : 2
and number 2 : 3
3.0+3.0 =
5.0
C:\Users\Filip>
Why doesn't puts() print in a single line, and how can keep the output on one line?
gets() includes the newline. Replace it with gets.strip. (Update: You updated your code, so if you're happy working with floats, this is no longer relevant.)
puts() adds a newline for each argument that doesn't already end in a newline. Your code is equivalent to:
print "#{number1}+#{number2} = ", "\n",
add(number1, number2) , "\n",
"\n"
You can replace puts with print:
print "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
or better:
puts "#{number1}+#{number2} = #{add(number1, number2)}"
Because puts prints a string followed by a newline. If you do not want newlines, use print instead.
Puts adds a newline to the end of the output. Print does not. Try print.
http://ruby-doc.org/core-2.0/IO.html#method-i-puts
You might also want to replace gets with gets.chomp.
puts "After entering something, you can see the the 'New Line': "
a = gets
print a
puts "After entering something, you can't see the the 'New Line': "
a = gets.chomp
print a

Ruby: Problem adding variables

I'm making a simple Ruby program to add the letters of a person's full name, but I don't know how to add the variables in the code.
puts "What's your first name?"
first = gets.chomp
puts "What's your middle name?"
middle = gets.chomp
puts "What's your last name?"
last = gets.chomp
puts "You have " + first.length.to_s + middle.length.to_s + last.length.to_s + " letters in your name."
If I put a name like "John Jacob Smith", I get "You have 455 letters in your name" instead of "You have 14 letters in your name".
puts "You have " + first.length.to_s + middle.length.to_s + last.length.to_s + " letters in your name."
first.length is 4 (a number), because "john" has 4 letters.
first.length.to_s is "4" (a string) because you turned the number into as string - too early.
In the rest of your code, you 'add' two other strings to it, to get "455"
4 + 5 = 9 # what you want
"4" + "5" = "45" # what you got
puts "You have " + (first.size + middle.size + last.size).to_s + " letters in your name."
# or
puts "You have #{first.size + middle.size + last.size} letters in your name."
or little more "Rubyish"
puts "You have " + [first, middle, last].inject(0){|s,w| s+=w.size}.to_s + " letters in your name."
Try this: puts "You have " + (first.length + middle.length + last.length) + " letters in your name."
That's because you're adding actual string representations of numbers instead of numbers thembselves. Check the #fl00r's answer

Resources