简体   繁体   English

class_eval如何将参数传递给方法

[英]class_eval how to pass parameter to method

How do I pass the parameter name in the following case..the name is being is evaluated before being passed to class_eval 如何在以下情况下传递参数名称...在传递给class_eval之前评估名称


class Foo

end

Foo.class_eval %Q{
def hello(name)
 p "hello #{name}"
end
}

Sorry about not giving the entire scenario... I just wanted to add a instance method dynamically to a class and that method should be able to take arguments... the above code would not compile complaining that the name is not defined as local variable when executing in irb.. 抱歉没有给出整个场景......我只想动态地向一个类添加一个实例方法,该方法应该能够接受参数...上面的代码不会编译抱怨名称没有被定义为局部变量在执行irb ..

Thanks 谢谢

The other answers are the "right" answer, but you could also just skip interpolating inside the p call: 其他答案是“正确”答案,但您也可以跳过p调用内插:

Foo.class_eval %Q{
  def hello(name)
    p "hello \#{name}"
  end
}

I thought you wanted to change the actual parameter name (possibly useful for completion or when using Pry on dynamic methods), here assuming it's in a global, but could also be passed into a method doing the class_eval : 我以为你想改变实际的参数名称(可能对完成或在动态方法上使用Pry时有用),这里假设它在全局中,但也可以传递给执行class_eval的方法:

Foo.class_eval %Q{
  def hello(#{$argname})
    p "hello \#{$argname}"
  end
}

Really simple: 真的很简单:

Foo.class_eval do
    def hello(name)
        p "hello #{name}"
    end
end

Try passing a block to class_eval instead of an array ( from this link ): 尝试将块传递给class_eval而不是数组( 来自此链接 ):

class Foo
end

Foo.class_eval {
  def hello(name)
    p "hello #{name}"
  end
}

You then can call the instance method hello in the usual fashion: 然后,您可以通常的方式调用实例方法hello

boo = Foo.new
boo.hello("you")

which produces: 产生:

>> boo.hello("you")
"hello you"
=> nil
class Foo
end

Foo.class_eval do
  define_method :hello do |name|
    p "hello #{name}"
  end
end

Foo.new.hello("coool") # => "hello coool"

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

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