Confused while using datatype in unless


#1

Hi,

Tried the exercise of "unless", it worked fine. But, I am confused on how to use a boolean here.

code

print "Are you hungry?? Say yes or no"
hungry = gets.chomp
unless hungry == yes
puts "I'm writing Ruby programs!"
else
puts "Time to eat!"
end

It will work if the yes is inside a "" that is string. My doubt is that, here yes/no is not string. but a boolean.

How to define a boolean here?

I learned if its integer, its will be like

eg : number = Integer(gets.chomp).

Please help me to learn how to use boolean like above?

output
Are you hungry?? Say yes or no no
undefined local variable or method `yes' for #


#2

If I understand your question correctly - you're trying to cast a variable's type to boolean? That's not of much use in Ruby, since only false and nil are considered false, everything else will be evaluated from the interpreter as true. (Although you can just do that with a double bang - !!hungry)

So if you use "yes", that's a string and it's true. If you use yes, that's a variable (in your case non-existant). If you'd like to use hungry's value itself you could just write

unless hungry
  puts "Something"
else
# continue here

In this case the interpreter will check the value of hungry. If it's either nil or false it will print out "Something". For everything else it will go in the else clause.