4

I read about Dave Thomas Ruby one liners

Its says

  # print section of file between two regular expressions, /foo/ and /bar/
      $  ruby -ne '@found=true if $_ =~ /foo/; next unless @found; puts $_; exit if $_ =~ /bar/' < file.txt

May I know how i can use this is my Ruby code and not from command line?

1 Answer 1

14

According to ruby CLI reference,

-n              assume 'while gets(); ... end' loop around your script
-e 'command'    one line of script. Several -e's allowed. Omit [programfile]

So, just copy the code snippet to a ruby file enclosed in gets() loop

foobar.rb

while gets()
   @found=true if $_ =~ /foo/
   next unless @found
   puts $_
   exit if $_ =~ /bar/
end

And execute the file using

ruby foobar.rb < file.txt

You can also replace IO redirect by reading the file programmatically

file = File.new("file.txt", "r")
while (line = file.gets)
   @found=true if line =~ /foo/
   next unless @found
   puts line
   exit if line =~ /bar/
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.