For the people who miss a pipeline in Ruby

For the people who miss the Elixir pipeline in Ruby, I made the following:

class Fixnum
  alias bitshift_right >>
  def >>(b)
    if b.respond_to?(:call)
      b.(self)
    else
      bitshift_right(b)
    end
  end
end

class Bignum
  alias bitshift_right >>
  def >>(b)
    if b.respond_to?(:call)
      b.(self)
    else
      bitshift_right(b)
    end
  end
end

class Object
  def >>(b)
    b.(self)
  end
end

class Proc
  def >>(b)
    b.(self.())
  end
end

It can be used as follows:

irb> b = Proc.new{|x| x*2}
irb> 10 >> b >> b >> b
80
irb> 128 >> 2 # Normal bit-shifting still works
32
irb> "foobar" >> lambda{|x| x.upcase} >> ->(x){x.length} >> b
12

:grin:

disclaimer: This might break some other classes that override the >> operator that I don’t know about. Please don’t use this in production code. Instead, consider switching to Elixir today ^^’!

4 Likes

Hi, I just presented about this topic at Goruco.

I implemented a gem called chainable_methods that presents a complete solution using Ruby’s proper dot notation, without the need for a secondary operator most of the times. Please take a look.

2 Likes

Wrapping all calls in a container object that applies the calls to the objects in the proper way is a really nice solution to this problem. Thank you for sharing your library :slight_smile:

@akitaonrails @Qqwy have a look for some inspiration: https://github.com/codequest-eu/codequest_pipes

1 Like