简体   繁体   English

如何插入红宝石方法名称

[英]How to interpolate in a ruby method name

Is it possible to interpolate in a method name? 可以插值方法名称吗? I'm trying to make this work def "cancel_#{appointment.id}" but having no luck. 我正在尝试使此工作定义为def "cancel_#{appointment.id}"但没有运气。 thanks 谢谢

Use define_method . 使用define_method

define_method "cancel_#{appointment.id}" do
  # your method body
end

Using define_method is best, but one could instead use the version of Module#class_eval which takes a string as an argument: 最好使用define_method ,但是可以改用Module#class_eval的版本,该版本将字符串作为参数:

class C
end

x = 'cat'
C.class_eval "def #{x}; 'meow'; end"
C.instance_methods.include?(:cat)
  #=> true
C.new.cat
  #=> 'meow'

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

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