Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Pipes In Ruby

DZone's Guide to

Pipes In Ruby

·
Free Resource
See Hopping Through Pipes and Closures, Object-oriented Pipelines: Implementation of Ruby pipes and also Fun with Procs in Ruby 1.9


# cf. http://whytheluckystiff.net/ruby/ruby-pipe.rb
require 'stringio'

module Piping
    def | proc; proc.call self; end
end
class IO
    include Piping
    def self.[](obj)
        if obj.respond_to? :read
            return obj
        else
            StringIO.new(obj.to_s)
        end
    end
end
class StringIO
    include Piping
end

wc = proc { |io| IO[io.inject(0) { |i, line| i += 1 }] }
grep = proc { |exp| proc { |io| IO[io.grep(exp)] } }

count = open("ruby-pipe.rb") | grep[/io/] | wc
p count.read


#-----------------------------------------


# cf. http://redhanded.hobix.com/inspect/hoppingThroughPipesAndClosures.html (in the comments)

module Piping
   def | proc 
        proc.call self
    end

    def self.[](obj)
        if obj.class.respond_to? :new
            obj.extend(Piping)
        else
       obj.class.extend(Piping)
        end
        obj
    end
end

class IO
  include Piping
end

wc = proc { |io| Piping[io.inject(0) { |i, line| i += 1 }] }
grep = proc { |exp| proc { |io| Piping[io.grep(exp)] } }

count = open("ruby-pipe.rb") | grep[/io/] | wc
p count



class Fun < Proc
  def call(*args)
    if args.size < arity.abs and arity != -1
      Fun.new{|*a|  call(*(args+a)) }
    else
      super
    end
  end
  alias_method :[], :call
end

def fun █
  Fun.new █
end

f = fun{|a, b, c| a * b / c }

f[10, 20, 30] == f[10][20][30]
#=> true
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}