What should be the logic to determine whether object is interger,float or string if the object is given as the input by the user?

If I understand correctly, you want to “guess” what type some data is that a user provided? The best way would probably be to use a regular expression. Otherwise, maybe only have “allowed” values and then you can more easily match them up.

foo = "bar"
case foo
when String
  puts "I'm a string"
  puts "Bad input"

Hi! I have a project for Edu Birdie, and I need some materials on Ruby. Can you suggest some?

Hello @lorenzomitchell,

I would recommend you to take a look here:

If you need something specific, please let me know.

I’ve read your website, as far as I see it’s about essays in general. You can ask Leo Green essay writer about this issue cause he is both developer and business owner.

First things first, inputs are just string. You have to use the .to_f and to_i methods to convert a String object to Float and Integer respectively.

1. The is_a?(Class) method:

The is_a? method is available on any object. It needs an argument, and it returns true or false:

a = STDIN.gets.to_f    # Note that if you use .to_f method, it's always going to be a `Float` object
a.is_a?(Float)    # => true

2. The kind_of?(Class) method

a = STDIN.gets.to_f 
a.is_a?(Integer)    # => false

3. The integer? method

a = STDIN.gets.to_f
a.integer?    # => false
a = a.ceil
a.integer?    # => true

4. The Case Subsumption Operator

a = STDIN.gets.to_f
Float === a    # => true

5. The Case Statement

The above codes can be used with an if statement:
puts :Float if Float === a

But you can also do something based on the class of the Object with a nice case statement.

a = STDIN.gets.to_f
r = case a
    when Float then :hi
    when Integer then :hello
    else :none

6. The class method:

This is a dirty trick. I just wanted you show you that you can use that. But I wouldn’t really prefer this trick on the above ones.

a = STDIN.gets.to_f 
a.class == Float          # => true
a.class == Integer        # => false
a.class == FalseClass     # => false

Hope this helps!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs