DonMB
DonMB

Reputation: 2718

Rails: undefined method `+' for nil:NilClass

I have this super simple code in my view:

<% @something.each do |something| %>

<% i = i+1 %>

<div class="row">
<div class="span1"><span class="badge untouched"><%= i %></span></div>
</div>

<% end %>

and get this error

undefined method `+' for nil:NilClass

I have the exact same code in another view and there it works! However, I'm new to rails and you see what I want to do. Maybe there is a more common way to increment an integer within an each loop? Where does this error come from?

Thanks for any help!

Upvotes: 2

Views: 14130

Answers (4)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

Define:

def nil.+ other; other end

Upvotes: 0

Dipali Nagrale
Dipali Nagrale

Reputation: 520

Initialize variable i = 0

<% i=0
i = i+1 %>

Upvotes: 1

Muhamamd Awais
Muhamamd Awais

Reputation: 2385

i is not initialized,

instead of each use each_with_index as follow

<% @something.each_with_index do |something, i| %>

<div class="row">
<div class="span1"><span class="badge untouched"><%= i %></span></div>
</div>

<% end %>

Upvotes: 4

MurifoX
MurifoX

Reputation: 15089

Well, i must have a value before you can increment it.

<% i = 0 %>
<% i = i+ 1 %>

Upvotes: 4

Related Questions