开发者

Metaprogramming instance methods - something wrong with the syntax?

NAMES = ['orange', 'pear']

  Fruit.class_eval do
    NAMES.each do |n|
        define_method "is_#{n}?" do
          self.name == Fru开发者_StackOverflow中文版it.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?


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?.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜