AntonAL
AntonAL

Reputation: 17410

nil values weirdness

I have faced a simple situation that I 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?

Upvotes: 0

Views: 227

Answers (4)

shingara
shingara

Reputation: 46914

You need parentheses:

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

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

Upvotes: 0

Rutger
Rutger

Reputation: 60

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.

Upvotes: 0

coder_tim
coder_tim

Reputation: 1720

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.

Upvotes: 0

Jed Schneider
Jed Schneider

Reputation: 14671

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

Upvotes: 1

Related Questions