更新时间:2023-02-14 10:59:57
Ruby 的众多优点之一是可以使用您自己的方法扩展现有类.这就是所谓的类重新开放"或猴子补丁(后者的含义不过,可能会有所不同).
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
所以,看看这里:
car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"
如您所见,require json
神奇地将方法 to_json
带入了我们的 Hash
.
As you can see, requiring json
has magically brought method to_json
to our Hash
.