openmind ☃   February 06, 2007  ☃  Ruby: Yoking Logical Operators and Blocks  ()

Ruby uses logical operators to execute multiple code sequences in the same way that bash does.

Operators symbolize logical operations in the evaluation of expressions…

expression1 && expression2
True if both expression1 and expression2 are true.

The && and || operators do not evaluate expression2 if the value
of expression1 is sufficient to determine the return value of
the entire conditional expression.

…and commands:

An AND list has the form

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

Provided that slice! returns true, the following are equivalent in ruby:

lines.slice!(0)
lines.each do |f|
  puts f[0] +  " " + f[1] if (f.length > 0)
end

lines.slice!(0) && lines.each do |f|
  puts f[0] +  " " + f[1] if (f.length > 0)
end

The second is pure syntactic sugar.

blog comments powered by Disqus