【问题标题】:2 different classes A and B . variable is declared in class A .I want to get value of variable in B2个不同的A类和B类。变量在 A 类中声明。我想在 B 中获取变量的值
【发布时间】:2015-11-27 08:58:23
【问题描述】:
class A
@i = 2
end

class B
puts @i
end

这是不同文件 a.rb 和 b.rb 中的两个类。我想在 B 类中打印@i。谁能帮我解决这个问题

【问题讨论】:

  • 你有什么问题?
  • 我的问题是如何将另一个类的变量的值打印到其他类中。我应该使用什么 require , load , include 。

标签: ruby class inheritance


【解决方案1】:

我建议你在使用 Ruby 的黑魔法之前考虑传统方式。

class A
  @i = 2
  def self.i
    @i
  end
end

class B
  puts A.i  #=> 2
end

如果暴露 A 的成员真的不可接受,那么请寻求 Andrey Deineko 的解决方案。

【讨论】:

    【解决方案2】:

    b.rb:

    require_relative 'a'
    
    class B
      puts A.instance_variable_get(:@i)
    end
    

    执行文件,你会得到输出:

    ruby b.rb
    #=> 2
    

    【讨论】:

    • 如果这是您问题的解决方案,请将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多