“Write a program which asks for a person’s favorite number. Have your
program add one to the number, then suggest the result as a bigger and
better favorite number. (Do be tactful about it, though.)”.
Any ideas? I’m getting “can’t convert fixnum into string” errors.
Here’s one of the many things I’ve tried, er, failed:
puts ‘What is your favorite number ?’
num = gets.chomp
better = ‘num’.to_i + 1
puts 'This is better: ’ + better + ‘.’
3rd line’s getting me. Can’t figure out how to add 1 to the response.
Hopefully, I’ll figure this out but any tips are welcomed. Thanks!
better is a fixnum (like the error says). In order to add it to the
string,
you’ll need to convert it to a string. Luckily, ruby gives you a nice
and
easy way to do it:
better.to_s will return the string version of better.
Also, I believe the line that that reads ‘num’.to_i return zero as
you’re asking the literal ‘num’ to return it’s integer value. Try it
without those quotes.
better = num.to_i + 1
puts 'This is a better number: ’ + better.to_s + ‘.’
Gregor’s solution is compact (good thing) but it’s too advanced for me
now.
What is it? Looks like a Python concocted commented out dictionary to
me…
Thanks again!
Gregor is using string interpolation, to insert the expression num + 1
into the output string. String interpolation works like this:
1.) if you do a .to_i to num, you dont need to chomp it.
2.) if you make ‘num’.to_i you try to transform the string num into
integer. it should be num.to_i, because you want the value of num and
not “num”.
3.) #{expression} in string will be replaced with its value in that
string.
try
(1…10).each do |number|
puts “Hallo there, Number #{number}!”
end
Write a program which asks for a person’s favorite number. Have your
#program add one to the number, then suggest the result as a bigger and
#better favorite number.
puts "What is your favorite number? "
num = gets.chomp
better = num.to_i + 1
puts 'This is a better number: ’ + better.to_s + ‘.’
Gregor’s solution is compact (good thing) but it’s too advanced for me
now.
What is it? Looks like a Python concocted commented out dictionary to
me…
Thanks again!
1.) if you do a .to_i to num, you dont need to chomp it.
2.) if you make ‘num’.to_i you try to transform the string num into integer.
it should be num.to_i, because you want the value of num and not “num”.
3.) #{expression} in string will be replaced with its value in that string.
try