Implicit and Explicit Conversion
Ruby objects are usually converted to other classes/types using to_*
functions.
For example, converting the string “42” to an integer is done with to_i
.
The following table shows the defined conversion methods of Ruby’s important core classes:
Class | Explicit Conversion | Implicit Conversion |
---|---|---|
Array | to_a |
to_ary |
Hash | to_h |
to_hash |
String | to_s |
to_str |
Integer | to_i |
to_int |
Float | to_f |
- |
Complex | to_c |
- |
Rational | to_r |
- |
Regexp | - | to_regexp |
IO | - | to_io |
Before
Some of Ruby’s core classes like String,
Array,
Hash,
Regexp has a try_convert
class method,
but it was missing in the case of Integer.
After
Starting with Ruby 3.1
try_convert
method is added to Integer class.
It converts the argument by to_int method without explicit conversions
like Integer()
.
try_convert
method converts the object into
an instance of the Integer class using the implicit conversion method to_int
.
If no implicit conversion method is defined,
it returns nil.
It also returns nil,
if the result of the conversion is nil,
or nil was passed as an argument.
Below is an example of how the try_convert method can be used in the Integer
x = 42
Integer.try_convert(x) # 42
# returns the argument if it's an Integer
x = "42"
Integer.try_convert(x) # nil
# returns nil when the argument does not respond to to_int
obj = Object.new
# sends to_int to the argument and raises TypeError if it's not a kind of Integer
Integer.try_convert(obj)
#=> TypeError: can't convert Object to Integer
obj = Object.new
# explicit conversion using to_i
def obj.to_i
1
end
# returns nil because `to_i` performs explicit conversion.
Integer.try_convert(obj)
#=> nil
obj = Object.new
# implicit conversion using to_int
def obj.to_int
1
end
# returns 1 because `to_int` performs implicit conversion.
Integer.try_convert(obj)
#=> 1
obj = Object.new
# implicit conversion using to_int, but we are not returning an integer.
def obj.to_int
Object.new
end
Integer.try_convert(obj)
#=> TypeError: can't convert Object to Integer
# Raises as error, as return type is not an integer.
When to Use What?
- Use
to_*
methods for explicit conversion. - Use
.try_convert
for implicit conversion.