Nil.- what the heck

Okay first off here’s the error:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.-

Here’s the code in the model:
def highest_bid
@bid = nil
@oldbid = 0
self.bids.each do |bid|
if @bid == nil
@bid = bid.max
else
if bid.max > @bid
@oldbid,@bid = @bid,bid.max
end
end
end
@oldbid += 1
@dif = @bid - @oldbid if @oldbid != 0
@bid -= @dif if @oldbid != 0
@bid
end

Two questions:
Is there an eaiser way to do this? What’s wrong with that line?

Bill Gates wrote:

Here’s the code in the model:
def highest_bid
@bid = nil
@oldbid = 0
self.bids.each do |bid|
if @bid == nil
@bid = bid.max
else
if bid.max > @bid

thik you’re missing an @ here, so it’s trying to do nil.max

Is there an eaiser way to do this?
this should do the trick, I think.

def highest_bid
bids.inject(0){|max, bid| [bid.max, max].max}
end

hth

Bill Gates wrote:

Here’s the code in the model:
def highest_bid
@bid = nil
@oldbid = 0
self.bids.each do |bid|
if @bid == nil
@bid = bid.max
else
if bid.max > @bid

think you’re missing an @ here, so it’s trying to do nil.max

Is there an eaiser way to do this?
this should do the trick, I think.

def highest_bid
bids.inject(0){|max, bid| [bid.max, max].max}
end

hth

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs