Get The Name Of A Local Variable

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

    No, because foo/bar/baz are not instance variables in your code. They are local variables (instance variables start with a @). There is a way to do it with instance variables and the Object#instance_variables method, though:

    @foo = 1
    @bar = 2
    @baz = 3
    
    instance_variables.each do |var|
      value = instance_variable_get var
      puts "#{var} = (#{value.class}) #{value}"
    end
    
    # outputs:
    # @foo = (Fixnum) 1
    # @bar = (Fixnum) 2
    # @baz = (Fixnum) 3
    

    To get the name of a particular instance variable, loop through all of the instance variables until you find one with a value that matches your instance variable.

提交回复
热议问题