开发者

Ruby assignment and comparison in one line?

It seems this doesn't work as e开发者_JAVA百科xpected:

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?


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.


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

c = Countries.first if c.nil?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜