Which should I use as I had just started learning Ruby for web development use, so shall we use this for such below example:
print "Type your chosen number?"
user_number = Integer(gets.chomp)
Or
print "Type your chosen number?"
user_number = gets.chomp.to_i
CodePudding user response:
It depends
If you need exception -- Integer(gets)
If no -- gets.to_i
or Integer(gets, exception: false)
In any case you don't need chomp
Integer("1") # => 1
Integer("1.0") # raise ArgumentError
Integer("blabla") # raise ArgumentError
Integer("blabla", exception: false) # => nil
"1".to_i # => 1
"1.0".to_i # => 1
"blabla".to_i # => 0
CodePudding user response:
In general you should ask an object to do something rather than do something to an object; the object knows best. object.do_thing
asks the object to do a thing. do_thing(object)
does the thing to the object, and assumes it knows best.
However, in this specific case, they are subtly different. The major difference is that String#to_i
will return 0 if you try to convert nonsense. Whereas Kernel#Integer
will throw an exception.
# Prints 0
p "not a number".to_i
# (file): invalid value for Integer(): "not a number" (ArgumentError)
p Integer("not a number")
In general you should prefer to raise an exception on failure, that is more important. Methods which do not throw exceptions on bad input make for difficult to find bugs, it's better to fail fast and as close to the actual problem as possible. If you want you can catch the exception.