首页 > 解决方案 > 类的实例方法

问题描述

我想看看类实例(类路径名)所独有的方法。我愿意:

Rails.root.class.methods(false)

我得到:

[:getwd, :pwd, :glob]

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

Rails.root.pwd

我得到:

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

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

谢谢!

标签: ruby-on-railsruby

解决方案


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

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

推荐阅读