seba
seba

Reputation: 153

define the method 'each' for nil:NilClass

undefined method 'each' for nil:NilClass

OK so, I know that there is hundreds questions that are talking about that.
I know what this error message means, and I know how to deal with that.

My question is : Is there a way to force the nil class to return an empty array?
My second question : Would it be safe ?

Thanks
Sebastien

Upvotes: 0

Views: 342

Answers (3)

fylooi
fylooi

Reputation: 3870

You can patch the class where you're calling each on:

class SomeItem
  def each(&block)
    [] unless super(&block)
  end
end

Or patch Enumerable directly, but i'd be leery of touching core classes that way.

Upvotes: 0

hedgesky
hedgesky

Reputation: 3311

1) Of course, you could patch nil (there is always only one nil object in Ruby thread, so you could patch it, and not NilClass):

def nil.each
  puts 'Hey'
end

nil.each #outputs 'hey'

2) But you should never do things like that, because it could break a lot of things inside a lot of libraries and even in Ruby itself.

Upvotes: 2

Milind
Milind

Reputation: 5112

If you are using something like @products..try ternary operator

@products = @products.present? ? @products : []

Yes it's safe if you handle it properly using empty and check the relevant values that you need before you proceed ahead or save them

Upvotes: 0

Related Questions