Get The Name Of A Local Variable

前端 未结 4 717
逝去的感伤
逝去的感伤 2020-12-30 11:43

When developing & debugging, I sometimes wish I could write a 1-liner that dumped the names, types & values of a bunch of variables. The problem is I don\'t know ho

4条回答
  •  死守一世寂寞
    2020-12-30 12:09

    Here's a little bit of debug code I use all over the place (I stick it in a separate file so that it can be required wherever needed). It can be used two ways. Passed one or more values, it simply inspects them and writes the result to $stderr. But passed a block which returns one or more things, it writes them out with their names.

    #!/usr/bin/ruby1.8
    
    def q(*stuff, &block)
      if block
        s = Array(block[]).collect do |expression|
          value = eval(expression.to_s, block.binding).inspect
          "#{expression} = #{value}"
        end.join(', ')
        $stderr.puts s
      else
        stuff.each do
          |thing| $stderr.print(thing.inspect + "\n")
        end
      end
    end
    
    i = 1
    q i       # => 1
    q {:i}    # => i = 1
    
    name = "Fred"
    q [name, name.length]         # => ["Fred", 4]
    q {[:name, 'name.length']}    # => name = "Fred", name.length = 4
    

    Note: The q function, and more, is now available in the cute_print gem.

提交回复
热议问题