What is ruby ​​-a command line switch?

On the man page:

-a Turns on auto-split mode when used with -n or -p. In auto-split mode, Ruby executes $F = $_.split at beginning of each loop. 

Some questions come to mind:

  • What happens when -a used without -n or -p ?
  • What is $F ?
  • What happens at the end of the cycle?
  • How to determine which character is selected on split ?
  • How to use -a ?

From another page:

 $F The variable that receives the output from split when -a is specified. This variable is set if the -a command-line option is specified along with the -p or -n option. 

I'm still not sure what the -a switch is. Appreciate the explanation, but appreciate some examples.

Some things I tried:

 $ echo foo_bar_bar | ruby -ae ruby: no code specified for -e (RuntimeError) $ echo foo_bar_bar | ruby -ap $ echo foo_bar_bar | ruby -ap '$_' ruby: No such file or directory -- $_ (LoadError) 
+5
source share
1 answer

Auto split mode is enabled using the -a switch. It allows you to process text, which is awk by default.
In auto-join mode, ruby ​​will read the files specified as arguments, or stdin one line at a time, and for each line:

  • automatically splits the string $_ into fields according to the field separator (indicated by -F )
  • assigns the result to a variable named $F
  • perform actions provided through the command line.

After processing all the lines, the program terminates or executes the END block. See this answer for.

Auto join mode is useful for working with text table files with a large number of records ( records are strings if the record separator section is not changed) and the number of fields delimiters in each row. For example, consider a file with content:

 ADG:YUF:TGH UIY:POG:YTH GHJUR:HJKL:GHKIO 

Then ruby -F: -a -n -e 'puts $F[2]' file prints the third field for each line:

 $ ruby -F: -a -n -e 'puts $F[2]' file TGH YTH GHKIO 

In this case, -F: sets the field separator to : $F is the array in which the fields live after writing ( $_ ). Actions after -e are performed for each line after it is split.

Ruby cli switches are very similar to perl switches. perl cli makes this function more convenient, see perldoc perlrun . For example, since -a not useful without -n (or -p ), in perl , -F implicitly includes -a , which, in turn, allows -n . This does not apply to ruby , all switches must be explicitly transferred. For examples of nice things you can do with this type of processing, find awk one liner .

In addition, ruby cli follows unix conventions to pass command line parameters :

Traditionally, UNIX command-line options consist of a dash followed by one or more lowercase letters.

Thus, the -a and -n and -e buttons can be combined to achieve the same result:

 $ ruby -F: -ane 'puts $F[2]' file TGH YTH GHKIO 

If this is interesting, see another ruby one liner.

+4
source

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


All Articles