Kapil Aggarwal
Kapil Aggarwal

Reputation: 105

Undefined method error - Rails - Ignoring while iterating

I have an array which contains the following objects 1. Model object - i.e. Tale(id: integer .....) 2. Symbols 3. Activerecord objects (instances of the models)

I need to regularly select different groups of objects from the array. I would like to be able to apply a method that is specific to a group and ignore the Undefined method on the others. Is that not intuitive. Anyone who responds to the method and then fulfills the condition is the right candidate. For example if i have

  array.select {|element| element.superclass == ActiveRecord::Base}

then i get Undefined method error from the symbols that may be in the array

How can i avoid this error. Instead of error handling is there some setting for just the select method.

Upvotes: 0

Views: 249

Answers (1)

devochka-volshebnitsa
devochka-volshebnitsa

Reputation: 138

You can use respond_to? method

array.select {|el| el.respond_to?(:superclass) && el.superclass == ActiveRecord::Base}

Or you can use try. It returns nil if an object doesn't respond to method or calls that method otherwise.

array.select {|el| el.try(:superclass) == ActiveRecord::Base}

Upvotes: 1

Related Questions