From: "jeremyevans0 (Jeremy Evans) via ruby-core" Date: 2024-10-22T19:58:57+00:00 Subject: [ruby-core:119591] [Ruby master Feature#15381] Let double splat call `to_h` implicitly Issue #15381 has been updated by jeremyevans0 (Jeremy Evans). There are certainly backwards compatibility issues from changing `**` from calling `to_hash` to `to_h`. I'm sympathetic to the argument that calling `to_h` fits better, as the conversion is explicit and not implicit, but the backwards compatibility costs are probably too high. Maybe in Ruby 4? One possible approach is defining `**@` as an operator method, something like: ```ruby class BasicObject def **@ = to_hash end ``` Using the unary `**` operator on an object would call the `**@` method, which should return a hash (or raise an exception). The method name itself is designed to be similar to `+@` and `-@`, which are called when you use the unary `+` and `-` operators. Users could then change the `**@` method to call `to_h` instead of `to_hash` if they want, and get the explicit conversion behavior (either for all objects, or for specific objects/classes). I proposed `*@` as the method called by the unary `*` operator in #2013, with a working patch, before `**` was introduced for keywords. This was the first issue I filed, back in 2009. It was eventually rejected as there was not much discussion on it, but it was still thought an interesting idea at the time it was rejected. ---------------------------------------- Feature #15381: Let double splat call `to_h` implicitly https://bugs.ruby-lang.org/issues/15381#change-110212 * Author: sawa (Tsuyoshi Sawada) * Status: Open ---------------------------------------- The single splat calls `to_a` implicitly on the object (if it is not an array already) so that, for example, we have the convenience of writing conditions in an array literal: ```ruby a = [ *(:foo if some_condition), *(:bar if another_condition), ] ``` And the ampersand implicitly calls `to_proc` on the object (if it is not a proc already) so that we can substitute a block with an ampersand followed by a symbol: ```ruby some_method(&:some_method_name) ``` Unlike the single splat and ampersand, the double splat does not seem to implicitly call a corresponding method. I propose that the double splat should call `to_h` implicitly on the object if it not already a Hash so that we can, for example, write a condition in a hash literal as follows: ```ruby h = { **({a: 1} if some_condition), **({b: 2) if another_condition), } ``` There may be some other benefits of this feature that I have not noticed yet. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/