DEV Community

Discussion on: Ruby 2.6 new feature: refine `#to_proc`

dhnaranjo profile image
Desmond Naranjo

I don't have a damn idea what I am looking at.

defman profile image
Sergey Kislyakov

My guess is &1 is 1.to_proc() and o is the receiver object (e.g. would do -> a[0])) and the sugar diabetes thingy is a.[].to_proc(). If I'm wrong please correct me @hanachin .

There's something similar in Kotlin though I like their implementation more.

hanachin profile image
Seiei Miyagi Author

That's correct!

& would implicitly call #to_proc to convert the object to Proc object.

Any object that implements the to_proc method can be converted into a proc by the & operator, and therefore con be consumed by iterators.

But before 2.6, #to_proc that defined in Refinements are ignored at & operator.

# foo.rb
using {
  refine(Integer) do
    def to_proc
      -> o { o[self] }

p 1.then(&0)
Enter fullscreen mode Exit fullscreen mode
% ruby -v foo.rb
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin17]
Traceback (most recent call last):
foo.rb:9:in `<main>': wrong argument type Integer (expected Proc) (TypeError)
Enter fullscreen mode Exit fullscreen mode

In 2.6, we can use #to_proc for & operator.

% ruby -v foo.rb
ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-darwin17]
Enter fullscreen mode Exit fullscreen mode