Reputation: 99
Instead of gets.chomp
, is there anything I can use to turn their response into a boolean?
puts "Do you like pizza? (yes or no)"
pizza = gets.chomp
if pizza == "yes"
pizza = true
else
pizza = false
end
I tried gets.to_b
and gets.bool
, but it doesn't seems to be working.
Upvotes: 0
Views: 2209
Reputation: 106882
I would just use get[0]
what returns the first character and allows you to accept y or yes:
puts 'Do you like pizza? (yes or no)'
pizza = gets[0] == 'y'
Or you can define a to_b
method on String
yourself:
class String
def to_b
# might want to add even more values to the list
%w( y yes true 1 ).include?(self.chomp.downcase)
end
end
'yes'.to_b
#=> true
'no'.to_b
#=> false
Upvotes: 3
Reputation: 1349
You can do something like this:
puts "Do you like pizza? [yes/no]:"
pizza = gets.chomp
case pizza
when 'y','Y','yes'
pizza = true
when 'n', 'N','no'
pizza = false
end
puts pizza
Upvotes: 1