codesnips’s posterous

« Back to blog

[Ruby] Grep with Ruby

ruby -ne 'puts $_ if $_ =~ /text/' *


-n places an implicit while gets ... end block

gets(separator=$/)    => string or nil
------------------------------------------------------------------------
     Returns (and assigns to +$_+) the next line from the list of files
     in +ARGV+ (or +$*+), or from standard input if no files are present
     on the command line. Returns +nil+ at end of file. The optional
     argument specifies the record separator. The separator is included
     with the contents of each record. A separator of +nil+ reads the
     entire contents, and a zero-length separator reads the input one
     paragraph at a time, where paragraphs are divided by two
     consecutive newlines. If multiple filenames are present in +ARGV+,
     +gets(nil)+ will read the contents one file at a time.

        ARGV << "testfile"
        print while gets

     _produces:_

        This is line one
        This is line two
        This is line three
        And so on...

     The style of programming using +$_+ as an implicit parameter is
     gradually losing favor in the Ruby community.

Comments (0)

Leave a comment...

 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     Connect     twitter