Saturday, 1 November 2008

Conditional statements

Before going any further, try this in the Ruby interactive console:

puts false or true        # prints false
puts true and false # prints true

Surprisingly, what gets printed is false and true respectively. What is going on? The problem is that and and or do not bind as strongly as the method call. In effect, you are doing this:

(puts false) or true
(puts true) and false

Contrast this with && and . These bind more tightly than the method call, and so behave as you would expect.

puts false  true        # prints true
puts true && false # prints false

More on operator precedence here:
http://www.techotopia.com/index.php/Ruby_Operator_Precedence

if and unless
While C and its derivatives have only if (condition) statement; Ruby supports two conditionals, if and unless, each in two formats:

if condition
statement
end

unless !condition
statement
end

statement if conditional

statement unless !conditional

You can optionally surround your conditional in brackets.

Ruby uses lazy conditionals. In the following code, if s is nil, Ruby knows that the expression will be false, and so does not test s.length > 10 - which is good, because that would throw an exception. This could, however, be a problem if you are changing the state of something in your condition; it might not change as often as you might imagine.

if !s.nil? and s.length > 10
puts 'Long string'
end


Conditional assignments can be done with the ||= operator.
s ||= "default"

The way this works is that nil counts as false, and in effect it say s = s || "default". If s is nil or false, then s becomes "default", otherwise it keeps its orignal value.

Ruby also supports the usual tertiary operator:
x = conditional ? value1 : value2

Struggling with Ruby: Contents Page

No comments: