grep method

The grep method takes an enumerable collection and applies a scalar or regexp to each element, returning a new array of the elements for which the scalar/regexp match. This is similar to select, except you specify a scalar/regexp to match against instead of a block.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# numbers matching 5-20:
@numbers.grep(5..20)
    #=> [5, 7, 6, 9, 8]

# numbers matching 5-20, multiplied by 2:
@numbers.grep(5..20){|x| x * 2}
    #=> [10, 14, 12, 18, 16]

Pet Inventory

# all pet names with the letter o:
@inventory.map(&:name).grep(/o/)
    #=> ["dog", "scorpion", "monkey", "rock"]

# all pet names with the letter o, capitalized:
@inventory.map(&:name).grep(/o/){|name| name.capitalize}
    #=> ["Dog", "Scorpion", "Monkey", "Rock"]

Pokey Things

# pokey things involving cactus:
@pokey_things.seek(0)
@pokey_things.grep(/cactus/).map(&:chomp)
    #=> ["cactus", "cactus holding poles with knives attached"]

# pokey things involving cactus, capitalized:
@pokey_things.seek(0)
@pokey_things.grep(/cactus/){|thing| thing.chomp.capitalize}
    #=> ["Cactus", "Cactus holding poles with knives attached"]

Heroku Log File

# javascript requests in heroku logs:
@requests.map(&:path).grep(/javascript/)
    #=> ["/javascript/jquery-2.1.0.min.js", "/javascript/jquery.jscroll.min.js", "/javascript/main.js", "/javascript/jquery-2.1.0.min.js", "/javascript/main.js", "/javascript/jquery.jscroll.min.js"]

# javascript requests in heroku logs, shortened:
@requests.map(&:path).grep(/javascript/){|path| path.gsub(%r!/javascript/!, '')}
    #=> ["jquery-2.1.0.min.js", "jquery.jscroll.min.js", "main.js", "jquery-2.1.0.min.js", "main.js", "jquery.jscroll.min.js"]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>