I'm doing a simple calculator using Ruby as practice. Everything is fine except how do I identify if a character/symbol I input is a number or not using if-else statement.
For example:
Enter first number: a
Error: Enter correct number
Enter first number: -
Error: Enter correct number
Enter first number: 1
Enter second number:b
Error: Enter correct number
Enter second number: 2
Choose operator ( -*/): *
The product is: 2
This is the code I input first:
print "Enter first number: "
x = gets.to_i
print "Enter second number: "
y = gets.to_i
print "Choose operator ( -*/): "
op = gets.chomp.to_s
I will use if-else statement to identify if the number input is a number or not
CodePudding user response:
Create a new String method
irb(main):001:0> class String
irb(main):002:1> def number?
irb(main):003:2> Float(self) != nil rescue false
irb(main):004:2> end
irb(main):005:1> end
irb(main):012:0> x = gets
1
=> 1
irb(main):013:0> x.number?
=> true
irb(main):009:0> x = gets
s
=> "s\n"
irb(main):010:0> x.number?
=> false
CodePudding user response:
This typical way to do this would be to match it with a regexp:
x = gets.chomp
if x.match?(/^\d $/)
puts "#{x} is a number"
else
puts "#{x} is not a number"
end
This tests if the given string matches the pattern ^\d $
, which means "start of line, one or more digit characters, then end of line". Note that this won't match characters like "," or "." - only a string of the digits 0-9. String#match? will return a boolean indicating if the string matches the given pattern or not.