0

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.

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.