bonum_cete
bonum_cete

Reputation: 4962

Assign variable value of object if not nil

I'm getting "Called id for nil.." error when I try the assignment below:

@selected = @items_design.items_categories[0].id

What I would like to do is assign

@selected = nil if @items_design.items_categories[0].id == nil

I tried this:

@selected = @items_design.items_categories[0].id || nil

and a couple of other attempts but no luck. Same error every time.

Upvotes: 2

Views: 675

Answers (3)

Izaaz Yunus
Izaaz Yunus

Reputation: 2828

The problem is @items_design.items_categories[0] is nil. So you could try this

@selected = nil
@selected = @items_design.items_categories[0].id unless @items_design.items_categories[0].nil

Upvotes: 0

Fred
Fred

Reputation: 8602

You must make sure the object @items_design.items_categories[0] itself isn't nil before sending the id message to that object. That's why your "like to do" version won't work, as it still sends the id message to an object that winds up being nil. This would work

@selected = nil if @items_design.items_categories[0].nil?

but it still isn't quite what you want. Try something like these:

@selected = @items_design.items_categories[0].nil? ? nil : @items_design.items_categories[0].id

or

if @items_design.items_categories[0].nil?
  @selected = nil
else
  @selected = @items_design.items_categories[0].id
end

Your second attempt

@selected = @items_design.items_categories[0].id || nil

isn't working because you always send the id message to the array result, even if it is nil.

Upvotes: 0

Dan
Dan

Reputation: 389

Ruby is telling you at @items_design.items_categories[0] is nil. How about this:

@selected = 
  if @items_design.items_categories[0]
    @items_design.items_categories[0].id
  else
    nil
  end

Or this:

@selected = @items_design.items_categories[0] ? @items_design.items_categories[0].id : nil

Edit: Adding another option from comments which is an even sweeter approach (thanks Daniël!):

@selected = @items_design.items_categories[0] && @items_design.items_categories[0].id

Upvotes: 1

Related Questions