繁体   English   中英

类的实例方法

[英]Class' instance methods

我想看看什么方法对于类实例(类路径名)是唯一的。 我愿意:

Rails.root.class.methods(false)

我得到:

[:getwd, :pwd, :glob]

然后,我调用其中一种方法:

Rails.root.pwd

我得到:

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

为什么我会收到这个错误? 如何仅查看 Pathname 实例的公共方法?

谢谢!

你必须在类上调用类方法,比如

Rails.root.class.pwd

OR

Pathname.pwd

获取所有实例方法(无祖先或单例):

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

您正在从Rails.root中获取方法,即Pathname的类方法:

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

要获取实例的方法,请使用:

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

或者,获取它的单例方法:(没有,它是一个普通的Pathname

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

请注意, Rails.rootPathname一个实例,并且已经代表您的应用程序的工作目录:

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

暂无
暂无

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

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