0
NAMES = ['orange', 'pear']

  Fruit.class_eval do
    NAMES.each do |n|
        define_method "is_#{n}?" do
          self.name == Fruit.find_by_name(n)
        end
    end
  end

For a fruit object, I want to be able to explicitly ask whether it's an orange or not, for example, by the fruit object's name attribute. When I call Fruit.find_by_name('orange').is_orange? I get false. What am I doing wrong?

2
  • 1
    I suspect you should be using instance_eval Commented Feb 6, 2011 at 15:28
  • You can easily verify that your method is being invoked. As such, it's not the metaprogramming that is at fault, but your logic within the method. Check your ActiveRecord(?) thinking Commented Feb 6, 2011 at 15:34

1 Answer 1

1
self.name == Fruit.find_by_name(n)

seems wrong to me. Shouldnt you check

self.name == n

??

And you should indeed use instance_eval.

Also, I think it would be more ruby-like to name your method orange? instead of is_orange?.

Sign up to request clarification or add additional context in comments.

1 Comment

ok, instance_eval makes sense for the question asked, but wouldn't it make even more sense to simply define those methods inside the class?

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.