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
