在调试具有某种复杂性的ruby代码时,很容易被堆叠的方法定义和命名与局部变量的冲突混淆.
我正在寻找一种快速的方法来找出哪个方法或变量响应表达式,例如any_expression.identify.
到目前为止我能找到的最好的是:
method(:happy)
#=> #<Method: Object(Helper)#happy>
method(:happy).source_location
#=> ["/home/somebody/project/lib/helper.rb", 9]
Run Code Online (Sandbox Code Playgroud)
不幸的是,一个局部变量(如happy=42)会先于,但method(:happy)仍将返回另一个方法.
有任何想法吗?
您不必使用前缀self.class.new.如果类没有没有参数的构造函数,它将无法工作.
local_variables.include?(:foo) # local variable
method(:foo) # method
Run Code Online (Sandbox Code Playgroud)
defined?关键字:
foo = 42
def bar; end
defined?(foo) # => "local-variable"
defined?(bar) # => "method"
Run Code Online (Sandbox Code Playgroud)
在pry中,你可以使用show-method:
show-method bar # =>
# From: (pry) @ line 104:
# Owner: Object
# Visibility: public
# Number of lines: 1
# def bar; end
Run Code Online (Sandbox Code Playgroud)
而且ls:
ls foo # =>
# Comparable#methods: between?
# Numeric#methods:
# +@ conj imaginary pretty_print_cycle rectangular
# abs2 conjugate nonzero? quo remainder
# angle eql? phase real singleton_method_added
# arg i polar real? step
# coerce imag pretty_print rect to_c
# Integer#methods:
# ceil downto gcdlcm next pred times to_r
# chr floor integer? numerator rationalize to_i truncate
# denominator gcd lcm ord round to_int upto
# Fixnum#methods:
# % ** -@ << == >= ^ div fdiv modulo succ zero?
# & + / <= === >> abs divmod inspect odd? to_f |
# * - < <=> > [] bit_length even? magnitude size to_s ~
Run Code Online (Sandbox Code Playgroud)
Ctrl+ r:foo ==> (反向搜索)`foo =':foo = 42