Get The Name Of A Local Variable

前端 未结 4 697
逝去的感伤
逝去的感伤 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:11

    foo = 1
    bar = "42"
    baz = Hash.new
    
    Varspec = Struct.new(:name, :type, :value, :inspect_str) do
      def to_s
        "#{name} = (#{type}) #{inspect_str}"
      end
    end
    
    lvars = local_variables.map {|lvar|
      lvar = lvar.to_s
      val = eval(lvar)
      val = val.dup rescue val
      Varspec.new(lvar, val.class, val, val.inspect)
    }
    
    puts lvars
    # baz = (Hash) {}
    # bar = (String) "42"
    # foo = (Fixnum) 1
    

    Or, you could just use a debugger. That's what they were invented for, after all.

提交回复
热议问题