Use ruby โ€‹โ€‹one liner from ruby โ€‹โ€‹code

I read about Dave Thomas Hack one liner

It says that

# 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 

Can I find out how I can use this my Ruby code, and not from the command line?

+4
source share
1 answer

According to the CLI ruby โ€‹โ€‹link,

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

So, just copy the code snippet into a ruby โ€‹โ€‹file enclosed in a gets () loop

foobar.rb

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

And run the file using

 ruby foobar.rb < file.txt 

You can also replace the IO redirection 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 
+14
source

Source: https://habr.com/ru/post/1383605/


All Articles