Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby debugging: How to find out which method or variable is responding?

Tags:

ruby

pry

When debugging ruby code with some complexity, it is easy to get confused by stacked method definitions, and by naming conflicts with local variables.

I am looking for a fast way to find out which method or variable responds to an expression, something like any_expression.identify.

The best I could find so far is:

method(:happy)
#=> #<Method: Object(Helper)#happy>

method(:happy).source_location
#=> ["/home/somebody/project/lib/helper.rb", 9]

Unfortunately a local variable (like happy=42) will precede, but method(:happy) will still return the other method.

Any ideas?

like image 671
bogl Avatar asked Jun 22 '26 09:06

bogl


1 Answers

You don't have to prefix with self.class.new. It wouldn't work if the class doesn't have constructor with no arguments anyway.

local_variables.include?(:foo) # local variable
method(:foo)                   # method


Another alternative is to use the defined? keyword:
foo = 42
def bar; end

defined?(foo) # => "local-variable"
defined?(bar) # => "method"

In pry, you can use show-method:

show-method bar # =>
  # From: (pry) @ line 104:
  # Owner: Object
  # Visibility: public
  # Number of lines: 1

  # def bar; end

And 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  ~


I don't think there is a way to check exactly where a local variable was defined. However, you could always reverse search in your console to see the line that defined it:

Ctrl + r: foo = => (reverse-i-search)`foo =': foo = 42

like image 68
ndnenkov Avatar answered Jun 24 '26 00:06

ndnenkov