【问题标题】:Ruby Metaprogramming : How to print local variable by and class variable defined instide constructorRuby Metaprogramming:如何打印局部变量和在构造函数中定义的类变量
【发布时间】:2017-09-30 10:56:58
【问题描述】:

我正在学习元编程并尝试解决这里给出的难题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 。 谁能帮我打印一下?

【问题讨论】:

    标签: ruby metaprogramming


    【解决方案1】:

    请检查此要点: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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 2014-08-01
      • 2012-03-29
      • 2017-08-29
      • 2018-01-20
      相关资源
      最近更新 更多