Ruby Metagrogramming:如何通过和类变量定义的Internextor打印本地变量



我正在学习元编程并尝试解决此处给出的拼图http://ruby-metaprogramming.rubylearning.com/html/exercise_1.html

class A
  def initialize
    @a = 11
    @@a = 22
    a = 33
  end
  @a = 1
  @@a = 2
  a = 3
end
Given the above class i have to print below ouptput
1
2
3
11
22
33

我无法打印33和3。谁能帮助我打印此?

请检查此要素:https://gist.github.com/greggawatt/8994520

$results = []
$results << class A
  def initialize
    @a = 11
    @@a = 22
    a = 33
  end
  @a = 1
  @@a = 2
  a = 3
end

在这里,我们使用instance_variable_get返回给定实例变量的值和class_variable_get的值以检索类变量的值。

$results << A.instance_variable_get(:@a)
$results << A.class_variable_get(:@@a)
puts $results.sort!
# 1
# 2
# 3
class B < A
  def initialize
    $results << super
  end
end

A.new
# define class A and get the instance variable 11 from the initialize method
$results <<  A.new.instance_variable_get(:@a)
# define class A and get the instance variable 22 from the initialize method
$results <<  A.class_variable_get(:@@a)
# here class B inherits from class A and use the `super` to call the `initialize` method of the parent class A, 
# this way you can retrieve the instance variable `a = 33` from the initialize method on Class A.
B.new
puts $results.sort!
# 1
# 2
# 3
# 11
# 22
# 33

最新更新