Skip to content

Instantly share code, notes, and snippets.

@rab
Forked from campbecf/ask_for_number.rb
Last active July 24, 2017 21:22
Show Gist options
  • Save rab/1815ac870e0aec4ff24990a4b6ce6f90 to your computer and use it in GitHub Desktop.
Save rab/1815ac870e0aec4ff24990a4b6ce6f90 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
def get_input(prompt = '--> ')
puts ''
puts 'Please enter a number, odd or even.'
print prompt
# if the end-of-input was reached and gets returned a nil
# or the word 'exit' or 'quit' appears (ignoring case) in the input
if (input = gets).nil? || /exit|quit/i =~ input
nil # just return a nil
else
input.to_i # otherwise, return the integer conversion
end
end
def test_user_input(number)
"'#{number}' is an #{number.even? ? 'EVEN' : 'odd'} number.\n"
end
while (number = get_input) # while the number I capture from get_input isn't nil (or false)
puts test_user_input(number)
end
@rab
Copy link
Author

rab commented Jul 24, 2017

Note that this is still not quite perfect as you can see by:

$ ruby ./ask_for_number.rb 

Please enter a number, odd or even.
--> 4
'4' is an EVEN number.

Please enter a number, odd or even.
--> 5
'5' is an odd number.

Please enter a number, odd or even.
--> nothing
'0' is an EVEN number.

Please enter a number, odd or even.
--> i quit

@rab
Copy link
Author

rab commented Jul 24, 2017

RegExp#match? doesn't exist in ruby 2.2.2 so use RegExp#=~ instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment