Project

General

Profile

Feature #11087

Method to retrieve {local,global,instance} variables as a Hash

Added by chancancode (Godfrey Chan) over 4 years ago. Updated over 4 years ago.

Status:
Feedback
Priority:
Normal
Target version:
-
[ruby-core:68963]

Description

Rails implemented Object#instance_values which returns all the instance variables as a hash.

This is used for serialization, but it is pretty useful for introspection, debugging and reporting as well. (For example, it could be used to implement something like this.)

I was going to propose an equivalent for local variables (and I suppose global variables too, for completeness), but if there are interest maybe we can do this on Ruby instead.

There are also some open questions:

  • Naming
  • Hash or iterator? (like Rails' Object#instance_value or like ObjectSpace.each_object)
  • Rails' Object#instance_values removes the leading @, are we going to do the same? (Probably not?)

History

Updated by ko1 (Koichi Sasada) over 4 years ago

  • Assignee set to matz (Yukihiro Matsumoto)

We could define something like that code:

class Object
  def instance_values
    instance_variables.inject({}){|r, val|
      r[val] = instance_variable_get(val); r
    }
  end
end

class C
  def initialize
    @a = @b = @c = nil
  end
end

p C.new.instance_values

Could you elaborate why do you want to introduce it?

Updated by ko1 (Koichi Sasada) over 4 years ago

  • Status changed from Open to Feedback

Also available in: Atom PDF