简体   繁体   English

如何根据一个实例变量,使用define_method在ruby中动态创建一个方法?

[英]How to create a method dynamically in ruby with define_method, depending on one instance variable?

I just don't get the answer to this question. 我只是没有得到这个问题的答案。 I want to create a method dinamically with a condition enter in the moment of the instance of the object. 我想在对象实例的时刻创建一个带有条件输入的动态方法。 I can create the method with other conditions that I tested, but in other circumstances it just doesn't work. 我可以在我测试过的其他条件下创建该方法,但是在其他情况下它根本无法工作。 Here is my code: 这是我的代码:

class Animal
  def initialize(live, swim)
    @live = live
    @swim = swim
  end
  def live?
    @live
  end
  def swim?
    @swim
  end
end

class Bird < Animal
  def initialize(live, swim, fly)
    super(live, swim)
    @fly = fly
  end

  define_metod(:flying) {puts "flying high"} if @fly
end

Bird.new(true, true, true).flying

I tried yet to various other ways to do that. 我还尝试了其他各种方法来做到这一点。 The error is that the method "flying" is not created: 错误是未创建方法“ flying”:

Traceback (most recent call last):
main.rb:23:in `<main>': undefined method `flying' for #<Bird:0x000056382015df98 @live=true, @swim=true, @fly=true> (NoMethodError)

@fly in define_method(:flying) {puts "flying high"} if @fly is a class instance variable . @flydefine_method(:flying) {puts "flying high"} if @fly类实例变量, define_method(:flying) {puts "flying high"} if @fly It doesn't exist when it's referenced (when the code is parsed), so nil is returned, resulting in the define_method statement not being executed. 当它被引用时(在分析代码时)它不存在,因此返回nil ,导致define_method语句不被执行。 The class instance variable @fly is unrelated to the instance variables @fly , just as @fly for one instance is unrelated to @fly for another instance. 类实例变量@fly是毫无关系的实例变量@fly ,就像@fly的一个实例是无关@fly的另一个实例。

See @Marcin's answer for how you can achieve your objective. 有关如何实现目标的信息,请参见@Marcin的答案。

If you'd still like to do that, try like this (simplified example): 如果您仍然想这样做,请尝试以下操作(简化示例):

class A
  def initialize(foo)
    define_singleton_method(:flying) { "flying high" } if foo
  end
end

Then: 然后:

> A.new(true).flying
 => "flying high"
> A.new(false).flying
NoMethodError: undefined method `flying' for #<A:0x0000000589a148 @foo=false>
  from (irb):24

This way the define_singleton_method is evaluated within the context of specific instance of the class, not the class itself, so you will be able to use any instance's instance variables you wish. 这样,在类的特定实例(而不是类本身)的上下文中评估define_singleton_method ,因此您将能够使用所需的任何实例的实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM