Sunday, November 30, 2014

User input stored as a string ($stdin.gets.chomp)

Following along with LRtHW on exercise 31 and I was wondering why the author was testing the user input as a string.

There was an exercise that covered gets.chomp but I never thought about it returning a string.  Then I found this documentation...


I was assuming that it would take the user input as is but the above link states...
  1. chomp is a string method (String#chomp).
  2. gets returns (gives you back) a string.
When I changed the code in the exercise from...

puts "You enter a dark room with two doors. Do you go through door #1 or door #2?"
print "> "
door = $stdin.gets.chomp
if door == "1"
  puts "There's a giant bear here eating cheese cake. What do you do?"
end

...to...

puts "You enter a dark room with two doors. Do you go through door #1 or door #2?"
print "> "
door = $stdin.gets.chomp.to_i
if door == 1
  puts "There's a giant bear here eating cheese cake. What do you do?"
end

..it worked as expected.

No comments:

Post a Comment