Ruby元编程:如何通过和类变量定义的instite构造函数打印局部变量
我正在学习元编程,并试图解决这里给出的难题 我无法打印33和3。 有人能帮我打印这个吗?请检查一下要点:Ruby元编程:如何通过和类变量定义的instite构造函数打印局部变量,ruby,metaprogramming,Ruby,Metaprogramming,我正在学习元编程,并试图解决这里给出的难题 我无法打印33和3。 有人能帮我打印这个吗?请检查一下要点: 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 $results = [] $results <&
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
$results = []
$results << class A
def initialize
@a = 11
@@a = 22
a = 33
end
@a = 1
@@a = 2
a = 3
end
$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