简体   繁体   中英

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

Thanks

The other answers are the "right" answer, but you could also just skip interpolating inside the p call:

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 :

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 Foo
end

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

You then can call the instance method hello in the usual fashion:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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