Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ruby one liners from ruby code

Tags:

ruby

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?

like image 606
vinothini Avatar asked Dec 10 '22 04:12

vinothini


1 Answers

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
like image 180
dexter Avatar answered Dec 24 '22 00:12

dexter