P
Phil Tomson
I'm working on the pattern matching section for
http://pleac.sourceforge.net/pleac_ruby/t1.html (an attempt to duplicate
the Perl Cookbook for several languages including Ruby).
The Perl code that needs to be duplicated in Ruby is:
while (<>) {
$in_header = 1 .. /^$/;
$in_body = /^$/ .. eof();
}
In Ruby first I tried:
File.open("filename"){|f|
f.each_line {|l|
in_header = $.==1 .. l=~/^$/
in_body = l=~/^$/ .. f.eof
puts "in_header: #{l}" if in_header
puts "in_body: #{l}" if in_body
}
}
But that give the following error:
ArgumentError: bad value for range
However, when I changed it to use the ternary operator, like so:
File.open("filename"){|f|
f.each_line {|l|
in_header = $.==1 .. l=~/^$/ ? true : false
in_body = l=~/^$/ .. f.eof ? true : false
puts "in_header: #{l}" if in_header
puts "in_body: #{l}" if in_body
}
}
It then works.
What gives? It seems that the flip/flop operator is evaluating to true or
false, why can't I just assign that value to in_header or in_body?
Phil
http://pleac.sourceforge.net/pleac_ruby/t1.html (an attempt to duplicate
the Perl Cookbook for several languages including Ruby).
The Perl code that needs to be duplicated in Ruby is:
while (<>) {
$in_header = 1 .. /^$/;
$in_body = /^$/ .. eof();
}
In Ruby first I tried:
File.open("filename"){|f|
f.each_line {|l|
in_header = $.==1 .. l=~/^$/
in_body = l=~/^$/ .. f.eof
puts "in_header: #{l}" if in_header
puts "in_body: #{l}" if in_body
}
}
But that give the following error:
ArgumentError: bad value for range
However, when I changed it to use the ternary operator, like so:
File.open("filename"){|f|
f.each_line {|l|
in_header = $.==1 .. l=~/^$/ ? true : false
in_body = l=~/^$/ .. f.eof ? true : false
puts "in_header: #{l}" if in_header
puts "in_body: #{l}" if in_body
}
}
It then works.
What gives? It seems that the flip/flop operator is evaluating to true or
false, why can't I just assign that value to in_header or in_body?
Phil