Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby command line one-liners sub vs. scan

Tags:

ruby

How come I can do

ruby -pe "sub /.*{((\d+\.){3}).*/, '\115'" < file.txt

but if I try scan instead of sub I get

-e:1:in <main>': undefined methodscan' for main:Object (NoMethodError)

This is confusing since sub isn't a method on Object either.

I also tried it the Perl way, something like

ruby -ne "/.*/; puts $1" <file.txt

but that didn't fly.

Where can I find the documentation covering this?

like image 244
Jonas Elfström Avatar asked Sep 30 '13 21:09

Jonas Elfström


1 Answers

sub is a method on Kernel, a module whose instance methods are globally available. This version of the method operates on the global variable $_ which contains the string last read by gets.

This is a totally different method than String#sub, which does a similar process but with an explicit string as the receiver, rather than implicit use of $_.

like image 92
Alex Wayne Avatar answered Nov 15 '22 08:11

Alex Wayne