Skip to content

Instantly share code, notes, and snippets.

@taylor
Created July 15, 2009 19:36
Show Gist options
  • Select an option

  • Save taylor/147928 to your computer and use it in GitHub Desktop.

Select an option

Save taylor/147928 to your computer and use it in GitHub Desktop.
# Printing only matching lines
l="john smith\nalice pena\nroot\nbob living\ntammy baroot\ncats"
q="root"
#string.each works by "splitting" on the end of line char... so this works "a\n\b\c"
l.each {|x| next unless x =~ /#{q}/ ; puts "x #{x}" }
# Create a new multi-line string w/only matching lines
s="abc\nlots of girls\nfat chickens\ngirls everywhere\nmeetings\ntaco\ngirl in bikini\ncats"
p "old string: #{s}"
q="girl"
ns = s.split("\n").map {|x| next unless x =~ /#{q}/; x}.compact.join("\n")
p "new string: #{ns}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment