|
This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
|
Original Post: Hopping Through Pipes and Closures
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
|
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded
|
|
Again, just an example of Ruby’s flexibility.
class IO
def | proc
proc[self]
end
end
Pass a File or Socket through a chain of procs with a pipe!
wc = proc { |io| io.inject(0) { |i, line| i += 1 } }
Like the above proc, which counts lines in a file.
count = open("/var/log/messages") | wc
Now, if you want to keep going and get these procs all chained together into a nice series of pipes and ongoing IO, see:
wc = proc { |io| IO[io.inject(0) { |i, line| i += 1 }] }
grep = proc { |exp| proc { |io| IO[io.grep(exp)] } }
count = open("/var/log/messages") | grep[/root/] | wc
p count.read
Which can be done in a myriad of fashions, but I chose to use StringIO in my script: ruby-pipe.rb. What fun. See Symbol.to_proc for a like kind of wonderment.
Read: Hopping Through Pipes and Closures