DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Pipes In Ruby
See <a href="http://redhanded.hobix.com/inspect/hoppingThroughPipesAndClosures.html">Hopping Through Pipes and Closures</a>, <a href="http://kronavita.de/chris/data/pipeline_rdoc.html">Object-oriented Pipelines: Implementation of Ruby pipes</a> and also <a href="http://pragdave.blogs.pragprog.com/pragdave/2008/09/fun-with-procs.html">Fun with Procs in Ruby 1.9</a>
# 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 &block
Fun.new &block
end
f = fun{|a, b, c| a * b / c }
f[10, 20, 30] == f[10][20][30]
#=> true





