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.