我有点困惑为什么以下代码实际上有效:
String.instance_eval do # self is set to String
[:readlink, :symlink?, :expand_path].each do |method| # self is still String
define_method(method) do # self is still String
File.send(method, self) # what exactly is this self?
end
end
end
"asdf".expand_path # => "C:/users/some_user/asdf"
我不明白为什么最后一行会这样工作。定义每个方法时,方法的主体不等于File.send(method, String)
?上述块实际上都没有改变self
。唯一更改的行self
是String.instance_eval
并且它更改self
为String
。