tags:

views:

61

answers:

2

It seems this doesn't work as expected:

if c = Countries.first.nil?
  ... do something
end

The comparison works but the assignment doesn't. Is there a way to do both the comparison and assignment in one line?

+5  A: 

This is what you really want:

if (c = Countries.first).nil?
  # ... do something
end

In your example, you will get c = (Countries.first.nil?), so c will be false or true.

You might actually write it like this:

unless (c = Countries.first)
  # ... do something
end

but caution! I would keep the () in place, because otherwise it will appear like you meant comparison, and the ruby interpreter will warn you.

I use this pattern sometimes, but use it sparingly, because it makes things less clear.

Peter
Why not as Reed had it? I assumed he wanted to assign c = true or false (from `.nil?`)... but I probably misread the intent of his question.
Andrew Vit
@Andrew The way Reed has it will set `c` to `Countries.first.nil?`, but he wanted to actually set `c` to `Countries.first` and then check `if c.nil?`
Daniel Vandersluis
This is a good example of why using parenthesis is important.
Greg
Or a better example of how splitting a statement into two doesn't hurt.
Chubas
+1  A: 

If you want to assign c to Countries.first if c is nil:

c = Countries.first if c.nil?
bryanweatherly
actually, if this is what you want you can just use `c ||= Countries.first`.
Peter