Ending Programs by pressing Enter key

Hello everyone,

I am new to Ruby and reading ‘Learn to Program: The pragmatic
programmers’

I would like to know how to make a program end by hitting the enter key
after leaving the gets parameter blank.

Kindly point me in the right direction.

Regards,

DE.

Dipo E. wrote in post #1138228:

I would like to know how to make a program end by hitting the enter key
after leaving the gets parameter blank.

-------------------------SNIP ----------------------
#encoding: UTF-8
#!/usr/local/bin/ruby

exit false if gets.chomp.empty?

puts ‘wasn’t empty’
-------------------------SNIP ----------------------

Ok, this is what I am trying to achieve

Write the program we talked about at the beginning of this chapter,
one that asks us to type as many words as we want (one word
per line, continuing until we just press Enter on an empty line)
and then repeats the words back to us in alphabetical order. Make
sure to test your program thoroughly; for example, does hitting
Enter on an empty line always exit your program? Even on the
first line? And the second? Hint: There’s a lovely array method
that will give you a sorted version of an array: sort. Use it!

and this is what I am doing

words = []
say = ‘nil’

while say != ‘’
puts 'say a word: ’
talk = gets.chomp
exit false if gets.chomp.empty?
words.push talk.to_s
end
puts words
puts words.sort

This is having me input two different words before putsing ‘Say a word’

Kindly point me in the right direction.

Redards,

DE.

On Feb 27, 2014, at 8:31 AM, Dipo E. [email protected] wrote:

that will give you a sorted version of an array: sort. Use it!
words.push talk.to_s
end
puts words
puts words.sort

This is having me input two different words before putsing ‘Say a word’

Kindly point me in the right direction.

When you call exit the program will exit, and I expect you want the
while loop to finish and still output the words. You can break out of a
loop using break. For example

x = 0
loop do
x +=1
break if x == 10
puts x
end
puts “done”

will print out the numbers 1 to 9 and then “done”.

Hope this helps,

Mike

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

Dear Dipo,

Easy catch.
You are getting and chomping 2 times!!!

You are doing…
talk = gets.chomp
exit false if gets.chomp.empty?

When you should be doing…
talk = gets.chomp
exit false if talk.empty?

Keep rubying!

Best regards,
Abinoam Jr.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs