Amit Erandole
Amit Erandole

Reputation: 12281

How do I access these inner variables in ruby?

I am trying to learn some basic ruby metaprogramming and have been given a class like this:

class A
  def initialize
    @a = 11
    @@a = 22 
    a = 33
  end

  @a = 1
  @@a = 2
  a = 3
end

I need to output these variables like so without modifying the class:

1
2
3
11
22
33

Here is my code so far:

p A.instance_variable_get(:@a) #=> 1
p A.class_variable_get(:@@a) #=> 2

A.new.instance_eval do
    puts @a #=> 11
end

Now how do I access the remaining variables?

Upvotes: 0

Views: 97

Answers (2)

Amit Erandole
Amit Erandole

Reputation: 12281

Ok so the final solution for those interested:

catcher = class A
  def initialize
    @a = 11
    @@a = 22
    a = 33
  end

  @a = 1
  @@a = 2
  a = 3
end

Bit of a cheat on that one but this works

puts A.class_eval { @a } #=> 1
puts A.class_variable_get :@@a #=> 2

puts A.new.instance_eval { @a } #=> 11

puts catcher #=> 3

puts A.new.send :initialize #=> 33 

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

class A
  def initialize
    @a = 11
    @@a = 22 
    a = 33
  end

  @a = 1
  @@a = 2
  a = 3
end

p A.instance_variable_get(:@a) # >> 1
p A.class_variable_get(:@@a) # >> 2

p A.new.instance_variable_get(:@a) >> 11

p A.class_variable_get(:@@a) # >> 22

Note that line to get var 22 is the same that gets var 2, because it is the same variable and its value was overwritten when you called A.new.

As for plain a variables, you can't get them, because they were local vars and don't exist anymore.

Upvotes: 2

Related Questions