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


puts "How many cookies do you want?"

cookies = gets.chomp

if cookies = 3

puts "Here are 3 cookies"


elsif cookies < 3

puts "You don't want that many cookies'


else "That's too many cookies!"



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"
  puts "That's too many cookies!"


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


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,


The # signifies a method, as in Class#method


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


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