Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

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.

Friday, November 28, 2014

Escape sequence b

I'm currently reading the website (online e-book) Learn Ruby the Hard Way and I'm on exercise 10.

It covers using the escape sequence with the various options.

I was stuck for a moment on why it wasn't working like I thought it should.

2.1.3 :001 > puts "backspace\b"
backspace
 => nil

I felt the entry should have removed the 'e' but the 'e' still showed up.  On another attempt, I got the result I was looking for.

2.1.3 :002 > puts "backspace\b "
backspac
 => nil

Putting a space between the letter 'b' and the double quote worked.  I have no technical explanation for this. My guess is that the backslash b is not given any space to "do it's thing".  I've googled but couldn't find anything on this topic.  Any comments welcome.  If I do find the explanation, I'll post what I find.