-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
      @@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

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

4

2 回答 2

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:: ("::" operator) 明确说明

于 2013-08-04T01:55:21.430 回答
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/

于 2013-08-04T01:49:31.243 回答