Hacker News new | past | comments | ask | show | jobs | submit login

You also have the Ruby solution of calling a `coerce` [0] method on the right hand side.

[0] - https://github.com/ruby/ruby/blob/0703e014713ae92f4c8a2b31e3...




I don't know Ruby very well, and I'm curious how this would work with my example above. It seems like Ruby's builtin number types, upon not knowing what to do, calls coerce on the right-side object. That right-side object returns a pair of new objects, and then the binary operation is called as a method on the left one of those?

If I've got that right, it sounds functionally similar to the Python way. It's a little awkward if you want different types depending on the operation. For instance, maybe A-B returns a different type than A/B. In both subtraction and division, it looks like Ruby would call coerce(), and coerce doesn't know the operator. Still that could build some smart placeholder type that then knows how to treat the operations differently...

For my example with Complex and Matrix types, it seems like the Complex type would need to implement the coerce protocol on its own. Maybe I've got that wrong, but does the coerce thing automatically happen for any type, or is that special behavior implemented by Ruby's Number types?


> If I've got that right

You did.

> it sounds functionally similar to the Python way

It definitely is, however it allows to handle all operators by defining a single method, so it's a bit more usable.

> does the coerce thing automatically happen for any type, or is that special behavior implemented by Ruby's Number types?

Only for number types. For other core types using binary operators, you have dedicated implicit conversion methods. For instance `"foo" + MyType.new` will try to call `MyType.new.to_str`.

`to_str` being specifically for implicit conversions, and `to_s` for explicit conversions. So implicit conversions won't happen unless specifically defined.


This approach seems nice in that it fast-tracks the common case and only delegates if needed.

> it allows to handle all operators by defining a single method,

That's nice and pragmatic too.

Back to the subject of this submission, I suspect the coerce idea could be bolted onto Wren without really breaking or changing much of anything (just an additional branch in the error handling of Wren's builtin Num type). That would allow Wren to grow it's own numpy-like library someday.


Ruby also let's you extend all object/classes - all the way up/down to Object.

I don't know that I think that's a very good idea, but at least it's possible.

It allows things like:

  require 'active_support/time'
  5.days.ago




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: