Skip to content
This repository has been archived by the owner on Feb 2, 2023. It is now read-only.

Consider implicit coercions, e.g. to_str for String #147

Open
wagenet opened this issue Mar 22, 2018 · 2 comments
Open

Consider implicit coercions, e.g. to_str for String #147

wagenet opened this issue Mar 22, 2018 · 2 comments

Comments

@wagenet
Copy link
Collaborator

wagenet commented Mar 22, 2018

For instance, instead of requiring that String values are actually T_STRING we could use implicit coercions (to_str) on the provided object. This would definitely be more Ruby-like in behavior.

Is this something we'd want to do? What are the drawbacks, if any?

@danielpclark
Copy link

danielpclark commented Jul 19, 2018

I wrote something like this for Rutie, but rather than using the to_str method call syntax I followed the try_convert design:

  • Array.try_convert
  • Hash.try_convert
  • String.try_convert
  • Regexp.try_convert
  • IO.try_convert

These do an implicit coercion or return a nil object. The trait in that project looks as follows:

pub trait TryConvert<T>: Sized {
    /// The type returned in the event of a conversion error.
    type Nil;

    fn try_convert(value: T) -> Result<Self, Self::Nil>;
}

I like using the Result type with a valid Ruby object in either branch because using the ? operator can allow for a direct return from Rust to Ruby where Rust doesn't have to handle the Result.

In that project I've only implemented this trait for the ruby string type so far. Implicit conversions are more of a rare thing but I believe they're worthwhile.

Hope my input was helpful!

@crazymykl
Copy link

try_convert is also a useful approach, but this sort of use case is literally to_str and friends' raison d'être, so I think the original proposal is a better fit.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants