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
When to Use What?
- Use
to_*
methods for explicit conversion. - Use
.try_convert
for implicit conversion.