Forum: Ruby Using the method "gets.chomp" variable gets String class.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0daa01e327de6c68ad4d6244759fec2f?d=identicon&s=25 Artemiy Baranov (artemiy)
on 2016-11-28 18:56
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" :(
0daa01e327de6c68ad4d6244759fec2f?d=identicon&s=25 Artemiy Baranov (artemiy)
on 2016-11-29 17:10
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
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2016-11-29 19:01
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.
0daa01e327de6c68ad4d6244759fec2f?d=identicon&s=25 Artemiy Baranov (artemiy)
on 2016-12-01 17:03
Thank you!
This topic is locked and can not be replied to.