Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Empty Input Doesn't Equal Nil?

  • Please log in to reply
1 reply to this topic

#1 quotidian


    CC Newcomer

  • Member
  • PipPip
  • 12 posts
  • Learning:Java

Posted 18 June 2012 - 05:31 AM

I'm trying to detect when the user doesn't enter anything and just presses the enter key. This is so I can break a loop that is adding each value then enter to an array.

However when I try and compare the variable with nil it still comes out as false.

At first I thought it was because gets was including the escape character \n at the end of the empty string, however when I use gets.chomp it still evaluates as false


Testing code
input = gets.chomp
puts (input == nil)

Terminal I/O

Press any key to continue . . .


PS. I'm a bit new to this so I mightn't have used the correct terms or explained that very well.
  • 0

#2 serpent


    CC Regular

  • Member
  • PipPipPip
  • 30 posts
  • Programming Language:C++, PHP

Posted 26 June 2012 - 12:14 AM

Your code does not work because gets.chomp does not return nil.
When user just presses the enter key gets returns "\n", so gets.chomp will remove end of line char leaving empty string.

This evaluates to true
input = gets.chomp
puts (input == '')

This is also correct
input = gets.chomp
puts (input.empty?)

  • 1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download