liveBook · Manning

Try_convert method

As explained in The Well-Grounded Rubyist, Fourth Edition

A try_convert method is a Ruby class method that conditionally invokes a compatible conversion method on an argument and returns nil when that method is unavailable.

A try_convert method is a class method that accepts one argument and conditionally calls a compatible conversion method on it. When that method is absent, it returns nil. section 9.2.1

Ruby provides this pattern for several classes:

  • Array.try_convert calls to_ary; Hash.try_convert calls to_hash; IO.try_convert calls to_io; Regexp.try_convert calls to_regexp; String.try_convert calls to_str. section 9.2.1
  • The conversion method must return an instance of the target class; otherwise try_convert raises TypeError rather than returning the incompatible object. section 9.2.1

An object becomes array-convertible

obj = Object.new Array.try_convert(obj) # => nil def obj.to_ary [1, 2, 3] end Array.try_convert(obj) # => [1, 2, 3] def obj.to_ary "Not an array!" end Array.try_convert(obj) # raises TypeError

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines lookup, missing-method behavior, supported pairs, and the TypeError raised for an incompatible conversion result.
Examples
Demonstrates Array.try_convert with an object lacking to_ary, gaining to_ary, and returning the wrong class.
What you can do after
Apply try_convert through Array.try_convert to test optional array conversion and recognize invalid conversion implementations.
How it connects
Connects Ruby objects, class methods, explicit conversion methods, Array, Hash, IO, Regexp, String, and TypeError.

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.