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
If you wish to test if the string represents an integer or float use Kernel#Integer or Kernel#Float with the optional second argument (a hash) having the value of the key :exception equal to false.
For example,
Integer('-123', exception: false)
#=> -123
Integer("0xAa", exception: false)
#=> 170
Integer('12.3', exception: false)
#=> nil,
Integer('12a3', exception: false)
#=> nil
Float('123', exception: false)
#=> 123.0
Float("1.2e3", exception: false)
#=> 1200.0
Float('12a3', exception: false)
#=> nil,
Float('1.2.3', exception: false)
#=> nil
Note
Integer("123\n", exception: false)
#=> 123
shows you don't have to chomp before testing if the string represents an integer (similar with Float).
Some of the examples illustrate a limitation or complication when using a regular expression to test whether a string represents an integer or float.
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
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.