Home > Software engineering >  Write a program which gets a number from a user and identify whether it is an Integer or a Float in
Write a program which gets a number from a user and identify whether it is an Integer or a Float in

Time:11-17

I am trying this :

print " Enter Value " num = gets.chomp

also tried .kind_of? but didn't work

if num.is_a? Float
print " Number is in float "

also tried .kind_of? but didn't work

else num.is_a? Integer
print " Number is in integer "

end

CodePudding user response:

Your problem here is that gets returns a String you can actually determine this based on the fact that you are chaining String#chomp, which removes the trailing "separator" which by default is return characters (newlines) e.g.

num = gets.chomp # User enters 1 
#=> "1" 

In order to turn this String into a Numeric you could explicitly cast it via to_i or to_f however you are trying to determine which one it is.

Given this requirement I would recommend the usage of Kernel#Integer and Kernel#Float as these methods are strict about how they handle this conversion. knowing this we can change your code to

print " Enter Value " 
num = gets.chomp
if Integer(num, exception: false) 
  puts "#{num} is an Integer"
elsif Float(num, exception: false) 
  puts "#{num} is a Float" 
else 
  puts "#{num} is neither an Integer or a Float"
end 

Note: the use of exception: false causes these methods to return nil if the String cannot be converted to the desired object, without it both methods will raise an ArgumentError. Additionally when I say these methods are strict about conversion a simple example would be Integer("1.0") #=> ArgumentError because while 1 == 1.0, 1.0 itself is a Float and thus not an Integer

CodePudding user response:

Some examples:

num = 6.6
num.is_a?(Integer)
=> false
num.is_a?(Float)
=> true
num = 6
num.is_a?(Integer)
=> true
num.is_a?(Float)
=> false

Minor note, #print is not the correct method to print to the screen. The correct method is #puts. So your code would look like this:

if num.is_a?(Float)
  puts 'Number is a float.'
elsif num.is_a?(Integer)
  puts 'Number is an integer.'
else
  puts 'Number is neither a float nor an integer.'
end

I suspect #gets returns a string though, which means you'll need to convert from a string into a numeric first.

  • Related