I understand that try_convert will try to use the implicit conversion on an object and return nil if the implicit conversion result is nil, if the object is nil or if no implicit conversion method exists. What would be a use case for try_convert? Is it meant to test an input and return it if it is of the intended type and nil otherwise, while avoiding getting a TypeError? Why not use is_a in this case?
What is the try_convert ruby method used for?
nr: #1 dodano: 2017-11-07 17:11
try_convert is, in my experience, rarely used. But the use case is to strictly convert objects, rather than more loosely using their representation. For example, consider:
There is no to_str method defined on the class because a regex does not act like a string.
Similarly, Array.try_convert(object) calls object.to_ary (not.to_a), and Hash.try_convert(object) calls object.to_hash (not.to_h).
So for example, if you wish to define a custom class that truly behaves like a String, then it is advisable to define a to_str method - and therefore (amongst other things) you can call String.try_convert on instances of this class.