Reputation: 537
I am new to Ruby. I have lines like this, asking a user to enter amount of money:
puts "Enter amount of money in $:"
goal = gets.chomp.to_f
How could I easily check if the user entered the correct amount in dd:cc format. Like 7.05 or 16.55 (excluding options like 45.343434).
Upvotes: 2
Views: 1368
Reputation: 9508
This accepts any number with two decimal places.
#file.rb
puts 'enter amount in dollars'
amount = gets.chomp
r = /^\d+\.\d\d$/
unless amount.match r
puts 'incorrect format, please try again'
end
Example
$ ruby file.rb
enter amount in dollars
444.884
incorrect format, please try again
Upvotes: 2
Reputation: 8602
Match your input string against the pattern you require. One example regular expression: optional leading negative, optional $, optional comma separation, mandatory two digit fraction of a dollar:
^\-?\$?[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}$
You can make simpler regular expressions. I recommend using an interactive tool like Rubular to play around and learn more about regular expressions.
Upvotes: 0