Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 类实例变量对子类不可用?_Ruby_Class Variables_Class Instance Variables - Fatal编程技术网

Ruby 类实例变量对子类不可用?

Ruby 类实例变量对子类不可用?,ruby,class-variables,class-instance-variables,Ruby,Class Variables,Class Instance Variables,我想在ruby中利用子类上的类方法,但那些依赖子实例变量的方法不起作用。有人告诉我“不要使用类变量!(@@)”,所以我不是。如何让classB做我想做的事,即打印出“1” 我希望它们都是使用受保护方法的“1” class A def initialize self.class.what_is_a end def self.what_is_a puts a end protected def self.a '1' end end

我想在ruby中利用子类上的类方法,但那些依赖子实例变量的方法不起作用。有人告诉我“不要使用类变量!(@@)”,所以我不是。如何让class
B
做我想做的事,即打印出
“1”


我希望它们都是使用受保护方法的
“1”

class A   
  def initialize
    self.class.what_is_a
  end

  def self.what_is_a
    puts a
  end

  protected 

  def self.a
    '1'
  end
end

class B < A
end


A.what_is_a # >> 1
B.what_is_a # >> 1
A.new # >> 1
B.new # >> 1
A类
def初始化
self.class.什么是
结束
定义self.u是什么
提出
结束
受保护的
自我定义
'1'
结束
结束
B类>1

hello,您考虑过使用受保护的方法而不是实例变量吗?您能告诉我这是如何工作的吗?根据具体的用例,类变量可能是合适的解决方案
B
a
是不同的实例,所以难怪您没有得到“1”。现在还不清楚你到底想做什么,所以我不能提供任何选择。我想我已经解释了我想做什么。我要B打印出“1”。也就是说,我希望B能够访问As类状态。该类状态的可能副本不使用实例变量(状态)。@SergioTulentsev同意,但不确定他是否需要它
"1"
nil
"1"
nil
class A   
  def initialize
    self.class.what_is_a
  end

  def self.what_is_a
    puts a
  end

  protected 

  def self.a
    '1'
  end
end

class B < A
end


A.what_is_a # >> 1
B.what_is_a # >> 1
A.new # >> 1
B.new # >> 1