ruby - 正常方法中的 "self"与单例方法中的 "self"?

标签 ruby singleton self

这两种情况下的 self 是否相同?

class Person
   def who_am_i?
     puts self       # self?
   end
end

ted = Person.new
def ted.singleton_who_am_i?
   puts self         # self?
end

ted.who_am_i?
ted.singleton_who_am_i?

最佳答案

是的,看起来是这样:

class Person
  def who_am_i?
    puts self.to_yaml
  end
end

ted = Person.new
def ted.singleton_who_am_i?
  puts self.to_yaml
end

ted.who_am_i?
--- !ruby/object:Person {}

ted.singleton_who_am_i?
--- !ruby/object:Person {}

关于ruby - 正常方法中的 "self"与单例方法中的 "self"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302238/

相关文章:

ruby - 获取 OpenSSL::SSL::SSLError:证书验证失败 - 具有最新 ca 包的事件

ruby - Ruby 的 .() 运算符如何工作?

android - Kotlin 中的同步单例

C++,静态与命名空间与单例

python - Python中类方法中调用实例方法

ruby-on-rails - Rails 服务器和 Rails 控制台因 : require': cannot load such file -- rack/protection (LoadError) 崩溃

ruby - 使用 Tk 和 Ruby 打开文件并取消时出错

java - TreeSet 如何作为成员变量在 Enum Singleton 中处理

Ruby - define_method 和闭包

perl - 谁能用 Perl 解释一下(我的 $self = shift)