What's wrong with my Ruby code? Please help :D


#1


puts "How many cookies do you want?"

cookies = gets.chomp

if cookies = 3

puts "Here are 3 cookies"

end

elsif cookies < 3

puts "You don't want that many cookies'

end

else "That's too many cookies!"

end


#2

End quote does not match opening quote.

And, there are too many end's.

The comparison is not correct.

gets.chomp returns a string, which also wrecks the comparison.

Study this example and see if you can spot the errors in your own code:

cookies = gets.chomp

if cookies.to_i == 3
  puts "Here are 3 cookies"
elsif cookies.to_i < 3
  puts "You don't want that many cookies"
else
  puts "That's too many cookies!"
end

#3

Thank you for your quick response. What does to to_i exactly do?


#4

I knew you would ask. Good that you do. It converts a string object to an integer, if it can.

It's too early to get into detail so I won't. You will learn as you go how everything in Ruby is an object. All objects follow certain blueprints called Classes which give them their natural properties and methods. Enough tech. .to_i is a String class method (a function that belongs to the class).

In the documentation I believe you will see it written as,

String#to_i

The # signifies a method, as in Class#method


#5

A post was split to a new topic: Another question - modulo


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.