Using the method "gets.chomp" variable gets String class

Using the method “gets.chomp” variable gets String class.

g = gets.chomp => “test”
g.class => String

g = gets.chomp => “123”
g.class => String

Can I get a “String” or “Fixnum” using a method gets.chomp depending on
the input?

g = gets.chomp => “1”
g.is_a? Numeric => false

If I used “to_i”, always will be “Fixnum” :frowning:

Happened, but maybe is a more elegant solution?

g = gets.chomp!
gi = g.to_i if g.count(“0-9”) > 0

gi.class => Fixnum

puts gi if gi.to_a? Numeric

It sounds like the user prompts are too vague if you could get such
varied input. The best solution if you can’t restrict their input is to
keep it as a String until you actually have to perform a non-String
operation on it. That way you can test the String for clues without
truncating it.

Thank you!

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