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.
Related
If I want a string of both words and numbers in ruby, such as "worda, wordb, 12, wordc, 10,"
do I need to first convert the number to a string ie.
a = 12.to_s?
Possible ways to mix strings and integers
It depends how you want to do it :
["worda", 10].join(', ')
"worda, #{10}"
"worda, %d" % 10
"worda" + ", " + 10.to_s
"worda" << ", " << 10.to_s
all return "worda, 10"
join and string interpolation will both call .to_s implicitely.
String + Integer
"worda" + 10
Is a TypeError, though, because there's no implicit conversion with +.
Otherwise "1" + 2 could be either "12" or 3. Javascript accepts it and returns "12", which is a mess IMHO.
String << Integer
Finally:
"worda, " << 10
is a valid Ruby syntax, but it appends the ASCII code 10 (a newline), not the number 10:
"worda, \n"
Ruby requires (approx.) strings to be of the same type, like most reasonable programming languages.
You have 1 solution.
"word" + 12.to_s
or
"word #{12}"
The second example is called string interpolation, and will call the method .to_s on any object passed in.
Yes, but you can do
"worda, wordb, #{num_1}, wordc, #{num_2},"
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.
Objective: Use the .each method on the odds array to print out double the value of each item of the array. In other words, multiply each item by 2.
Make sure to use print rather than puts, so your output appears on one line.
code:
odds = [1,3,5,7,9]
odds.each do |x|
x *= 2
print "#{x}"
end
Doing this exercise on Codecademy, I'm rather confused about the syntax as why there needs to be a #{} surrounding the x and why can't it just be: print "x" or print #x". What are the roles of the hash and brackets? It perplexes me as why ruby doesn't print out "#{X}" rather than the "x" number multiplied by 2 due to it being surrounded by quotation marks? Previous exercises also featured both hashes and curly brackets #{user_input} where the console printed whatever we typed rather than print out "#{user input}" itself.
You can't do print "x" and expect it prints the value of the x object. What if you wanted to print the x letter? So, we need interpolation for that.
But interpolation used in that way has just the collateral effect to make xa string. You can do the same without interpolation:
print x
Anyway, I'd probably do
odds = [1,3,5,7,9]
odds.each { |x| print x * 2 }
About interpolation: you can use it when you should concatenate several strings and it would be ugly. For instance
puts name + " " + surname
puts "#{name} #{surname}"
I prefer the latter
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.
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.