How can I tell if someone has enter nothing in a gets prompt, they only
press enter. I though maybe it was nil, but that doesn’t seem to work. I
though this was going to work nicely, but doesn’t.
Building and sorting an array.
array = []
word = ‘foo’
while word != nil
puts ‘Enter a word’
word = gets
array.push word
end
puts array.sort
Sorry I may have gotten it, check this out.
Building and sorting an array.
array = []
puts ‘Enter a word’
word = gets.chomp
while word != ‘’
array.push word
puts ‘Enter a word’
word = gets.chomp
end
puts array.sort
You might want to look into String#empty?
Am 29.03.2013 16:55, schrieb Phil H.:
How can I tell if someone has enter nothing in a gets prompt, they only
press enter. I though maybe it was nil, but that doesn’t seem to work. I
though this was going to work nicely, but doesn’t.
The string will be “\n” (a string that contains only a newline):
if gets == “\n”
or
if gets.chomp.empty?
will work.
Phil H. wrote:
puts ‘Enter a word’
word = gets
array.push word
end
puts array.sort
Using enter even with no other character will return a \r\n or \n
depending upon your operating system
Tom R.
On Fri, Mar 29, 2013 at 5:42 PM, Joel P. [email protected]
wrote:
You might want to look into String#empty?
That alone is not sufficient. You need to at least throw String#chomp
in
the mix:
array = []
word = nil
do
puts ‘Enter a word’
word = gets.chomp # cut off line endings
array.push word unless word.empty?
end until word.empty?
puts array.sort
Another approach would verify that the string does indeed contain a
word:
…
do
puts ‘Enter a word’
word = gets.chomp # cut off line endings
array.push word unless /\A\w+\z/ =~ word
end until word.empty?
We can also avoid the duplicate check:
array = []
word = nil
loop do
puts ‘Enter a word’
word = gets.chomp # cut off line endings
break if word.empty?
array.push word
end
puts array.sort
Kind regards
robert
Robert K. wrote in post #1103733:
You might want to look into String#empty?
That alone is not sufficient. You need to at least throw String#chomp
in the mix:
I he was already using chomp, so I didn’t see a point in mentioning it
On Sat, Mar 30, 2013 at 9:16 AM, Joel P. [email protected]
wrote:
Robert K. wrote in post #1103733:
You might want to look into String#empty?
That alone is not sufficient. You need to at least throw String#chomp
in the mix:
I he was already using chomp, so I didn’t see a point in mentioning it
Right you are. I am sorry, I didn’t notice Phil added it in his second
post.
Cheers
robert