开发者

nil values weirdness

I have faced a simple situation that I开发者_如何学C can't figure out.

I have to decide whether to show the "more" link, depending of the articles count.

The code is simple:

@no_more = offset + length >= Article.count

@no_more variable equals to nil sometimes. I see in the debugger that offset = 0, length = 10 and Article.count = 12

But the expression above gives nil.

Even this doesn't help:

@no_more = false if @no_more.nil?

@no_more will still be nil.

Why does it behave like this?


what about not-not assignment?

ruby-1.8.7-p299 > @no_more
 => nil 
ruby-1.8.7-p299 > !!@no_more
 => false 
ruby-1.8.7-p299 > @no_more = true
 => true 
ruby-1.8.7-p299 > !!@no_more
 => true


Make sure that you are not resetting the @no_more variable somewhere else in your controller or view, especially if you are doing a redirect.


Try printing @no_more.class and check if it really is a NilClass and not a FalseClass.

I say this because I had the same problem the other day. This was with the debugger in netbeans (and jruby for that matter), but the debugger did not seem to understand the FalseClass.

for example this code:

p = false
puts p.class

For me this ofcourse printed FalseClass, but the debugger insisted p was a NilClass. I confirmed with "kind_of?" that it really was a FalseClass.

You could try checking the same things.

@no_more.kind_of?(FalseClass)

Just thought I'd mention this in case it's the same problem as I had. It kept me busy half the night trying to figure out wtf was going on.


You need parentheses:

@no_more = ((offset + length) >= Article.count)

The precedence works oddly without them, so Ruby interprets your code in that way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜