The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hopping Through Pipes and Closures

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Hopping Through Pipes and Closures Posted: Nov 19, 2005 1:38 PM
Reply to this message Reply

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

Advertisement

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

Topic: Penny-Arcade on Rails Previous Topic   Next Topic Topic: MenTaL on Monads in Ruby

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use