根据对象的类使用正确的类变量

时间:2013-08-04 01:17:54

标签: ruby

我有以下课程:

class A
  @@one = {1 => "hen", 2 =>  "di", 3 =>  "tri", 4 =>  "tetra"}
  @@two = {5 =>  "penta", 6 =>  "hexa", 7 =>  "hepta", 
          8 =>  "octa", 9 =>  "nona"}

  def initialize(value)
    @value = value
  end

  def to_s
    value = @value
    if value <=4
      @@one[value]
    else
      @@two[value]
    end
  end
end

class B < A
  @@one = {1 => "meth", 2 =>  "eth", 3 =>  "prop", 4 =>  "but"}

  def initialize(value)
    @value = value
  end
end

以及以下驱动程序:

require_relative 'A.rb'
require_relative 'B.rb'

puts A.new(1)
puts B.new(1)

我希望输出为:

hen
meth

但A类变量@@ one被B类变量@@ one覆盖。所以我的输出是:

meth
meth

我尝试了类实例变量,类常量和类变量。但这两种解决方案都不起作用。

2 个答案:

答案 0 :(得分:1)

试试这个(因为你说“我尝试了类实例变量,类常量和类变量。但是两种解决方案都不起作用。”),我给出了一个使用类常量的解决方案,最适合这种特殊情况:

class A
 ONE = {1 => "hen", 2 =>  "di", 3 =>  "tri", 4 =>  "tetra"}
 TWO = {5 =>  "penta", 6 =>  "hexa", 7 =>  "hepta", 
      8 =>  "octa", 9 =>  "nona"}

def initialize(value)
  @value = value
end

def to_s
 value = @value
  if value <=4
   self.class::ONE[value]
  else
   self.class::TWO[value]
end
end

class B < A
 ONE = {1 => "meth", 2 =>  "eth", 3 =>  "prop", 4 =>  "but"}

 def initialize(value)
  @value = value
 end
end
解释:在这种情况下,子案例会覆盖父类中的内容,因此如果您想使用父类中的某些内容(由子类重写),则必须通过class_name ::(“::”运算符)明确说明)

答案 1 :(得分:0)

这个怎么样?

class A
  class << self; attr_accessor :one end
  class << self; attr_accessor :two end

  @one = {1 => "hen", 2 =>  "di", 3 =>  "tri", 4 =>  "tetra"}
  @two = {5 =>  "penta", 6 =>  "hexa", 7 =>  "hepta", 8 =>  "octa", 9 =>  "nona"}

  def initialize(value)
    @value = value
  end

  def to_s
    value = @value
    if value <=4
      self.class.one[value]
    else
      self.class.two[value]
    end
  end
end

class B < A
  @one = {1 => "meth", 2 =>  "eth", 3 =>  "prop", 4 =>  "but"}

  def initialize(value)
    @value = value
  end
end

puts A.new(1)
puts B.new(1)

关于这个主题的好文章:http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/