Question: What is the try_convert ruby method used for?


What is the try_convert ruby method used for?

Answers 1
Added at 2017-11-07 17:11

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?

Answers to

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:

/foo/.to_s #=> "(?-mix:foo)"
/foo/.to_str #=> NoMethodError: undefined method `to_str' for /foo/:Regexp

String.try_convert(/foo/) #=> nil

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.

Source Show
◀ Wstecz