猴子补丁vs class_eval? [英] monkey patching vs class_eval?

查看:83
本文介绍了猴子补丁vs class_eval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class String
  def hello
    "world"
  end
end

String.class_eval {
  def world
    "hello"
  end
}

"a".world
=> "hello"
"b".hello
=> "world"

他们似乎在做同样的事情-向现有的类中添加一个方法.那有什么区别?

They seems to do the same thing -- adding a method to a existing class. So what's the difference?

推荐答案

使用class_eval您可以做更多动态的事情:

With class_eval you can do more dynamic things:

>> met = "hello" #=> "hello"
>> String.class_eval "def #{met} ; 'hello' ; end" #=> nil
>> "foo".hello #=> "hello"

这篇关于猴子补丁vs class_eval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆