Hacker News new | past | comments | ask | show | jobs | submit login
Making Ruby Yours (conjur.org)
4 points by jonahx on July 25, 2018 | hide | past | favorite | 1 comment



> Taking inspiration from the Unix pipe | and Elixir’s pipe operator |>, we can refine ruby’s unused >> method on the Array and Symbol classes and write:

Ruby 2.5 introduced yield_self[1] (which is likely (or is) to be aliased/renamed to then[2]) which can accomplish more or less the same thing as the pipeline operator (it's just unfortunately not as sexy as the |> operator)

  some_var
    .yield_self { |v| foo(v) }
    .yield_self { |v| bar(v) }
    .yield_self { |v| baz(v) }
Or even more succinctly/ugly (depending on who you ask) with the coming soon then alias and using/abusing the &method(:name) syntax:

  some_var
    .then(&method(:foo))
    .then(&method(:bar))
    .then(&method(:baz))
One of the reasons I love Ruby, and some people really hate Ruby, is how easy it easy to modify the language to your task/preferences. So, you could just define alias or method proxy for >> (or whatever) to yield_self to get a cleaner, less verbose syntax (though I wouldn’t do this is code that others are also working on):

  module PipelineOperator
    refine Object do
      def >>(next, &block)
        yield_self block ? &block : &proc { |v| next(v) }
      end 
    end
  end
 
  module Foo
    using PipelineOperator

    def method
      foo >> bar >> baz
    end
  end
[1] https://ruby-doc.org/core-2.5.1/Object.html#method-i-yield_s...

[2] https://bugs.ruby-lang.org/issues/14594




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: