简体   繁体   English

类的实例方法

[英]Class' instance methods

I want to see what methods are unique to a class instance (class Pathname).我想看看什么方法对于类实例(类路径名)是唯一的。 I do:我愿意:

Rails.root.class.methods(false)

And I get:我得到:

[:getwd, :pwd, :glob]

Then, I call one of the methods:然后,我调用其中一种方法:

Rails.root.pwd

And I get:我得到:

NoMethodError (undefined method `pwd' for #<Pathname:/Users/borjagvo/workstation/npilookup>)

Why do I get this error?为什么我会收到这个错误? How can I see the public methods for instances of Pathname only?如何仅查看 Pathname 实例的公共方法?

Thanks!谢谢!

You have to call class methods on class, like你必须在类上调用类方法,比如

Rails.root.class.pwd

OR

Pathname.pwd

For getting all instance methods (no ancestors nor singleton):获取所有实例方法(无祖先或单例):

pry(main)> Rails.root.class.instance_methods(false) # OR Pathname.instance_methods(false)
=> [:write, :join, :+, :/, :as_json, :directory?, :exist?, :readable?,
    :readable_real?, :world_readable?, :writable?, :writable_real?, 
    :world_writable?, :executable?, :executable_real?, :file?, :size? .....]
# Then you can call above methods on instance of a Pathname
 pry(main)> Rails.root.size?
 => 1248

You are fetching the methods from the class of Rails.root , ie Pathname 's class methods:您正在从Rails.root中获取方法,即Pathname的类方法:

Rails.root.class        #=> Pathname
Pathname.methods(false) #=> [:glob, :getwd, :pwd

To get the instance's methods, use:要获取实例的方法,请使用:

Rails.root.methods
#=> [:mountpoint?, :root?, :each_filename, :descend, :ascend, :write, ...]

Or, to get its singleton methods: (there are none, it's an ordinary Pathname )或者,获取它的单例方法:(没有,它是一个普通的Pathname

Rails.root.methods(false)
#=> []

Note that Rails.root is an instance of Pathname and already represents your app's working directory:请注意, Rails.rootPathname一个实例,并且已经代表您的应用程序的工作目录:

Rails.root
#=> #<Pathname:/Users/borjagvo/workstation/npilookup>

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

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