mbigras mbigras - 1 month ago 10
Ruby Question

Why would you use the ruby -l (ELL) flag?

from the man pages


(The lowercase letter ``ell''.) Enables automatic line-ending
processing, which means to firstly set $\ to the value of $/, and
secondly chops every line read using chop!.


And I can construct an example of the switch working:

➜ ruby-ell cat app.rb
p "hello world"
p "$\: #{$\}"
p "$\: #{$/}"
➜ ruby-ell ruby app.rb
"hello world"
"$: "
"$: \n"
➜ ruby-ell ruby -l app.rb
"hello world"
"$: \n"
"$: \n"


So I can see that the
-l
is loading
$/
into
$\
but why would you want to do that? Would love some examples and/or references to instances of this switch being used :)

Answer

It's probably most useful with -n or -p. It allows you to edit the current line ($_) without caring about the trailing newline. For example, to append "foo" to the end of each line:

$ echo -e "1\n2\n3" | ruby -lnpe '$_ << "foo"'
1foo
2foo
3foo

Without -l, it would append "foo" after the newline character:

$ echo -e "1\n2\n3" | ruby -npe '$_ << "foo"'
1
foo2
foo3
foo

And without setting the record separator, a simple chop! would just remove all newlines:

$ echo -e "1\n2\n3" | ruby -npe '$_.chop!; $_ << "foo"'
1foo2foo3foo

Note that you can specify the input record separator:

echo -n "1-2-3-" | ruby -l055 -npe '$_ << "foo"'
1foo
2foo
3foo

055 is the octal value for -.

You can also specify the output separator via -0:

echo -n "1-2-3-" | ruby -0056 -l055 -npe '$_ << "foo"'
1foo.2foo.3foo.

All these switches come from Perl, see http://perldoc.perl.org/perlrun.html#Command-Switches