shell - Ruby Command Line Implicit Conditional Check -
i ran following bash shell:
echo 'hello world' | ruby -ne 'puts $_ if /hello/'
i thought typo @ first, outputted hello world
surprisingly.
i meant type:
echo 'hello world' | ruby -ne 'puts $_ if /hello/ === $_'
can give explanation, or point documentation, why implicit comparison $_
?
i'd note:
echo 'hello world' | ruby -ne 'puts $_ if /test/'
won't output anything.
the ruby parser has special case regular expression literals in conditionals. (i.e. without using e
, n
or p
command line options) code:
if /foo/ puts "true!" end
produces:
$ ruby regex-in-conditional1.rb regex-in-conditional1.rb:1: warning: regex literal in condition
assigning matches regex $_
first, this:
$_ = 'foo' if /foo/ puts "true!" end
produces:
$ ruby regex-in-conditional2.rb regex-in-conditional2.rb:2: warning: regex literal in condition true!
this (poorly documented) exception normal rules ruby conditionals, that’s not false
or nil
evaluates truthy.
this applies regex literals, following behaves might expect conditional:
regex = /foo/ if regex puts "true!" end
output:
$ ruby regex-in-conditional3.rb true!
this handled in parser. searching mri code text of warning produces single match in parse.y
:
case node_dregx: case node_dregx_once: warning_unless_e_option(parser, node, "regex literal in condition"); return new_match2(node, new_gvar(rb_intern("$_")));
i don’t know bison, can’t explain going on here, there clues can deduce. warning_unless_e_option
function suppresses warning if -e
option has been set, feature discouraged in normal code can useful in expressions command line (this explains why don’t see warning in code). next line seems constructing parse subtree regular expression match between regex , $_
global variable, contains “[t]he last input line of string gets or readline”. these nodes compiled regular expression method call.
that shows happening, i’ll finish quote kernel#gets
documentation may explain why such obscure feature
the style of programming using $_ implicit parameter gradually losing favor in ruby community.
Comments
Post a Comment