首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >常量与实例变量与实例方法

常量与实例变量与实例方法
EN

Stack Overflow用户
提问于 2014-08-25 04:38:56
回答 1查看 342关注 0票数 2

我有一个基类A,它包含一个公共方法,它使用A.的后代提供的数组,数组是:

  • 仅由基类A中定义的方法使用。
  • 常量,但也有一些特殊情况下,它是不同的。

我应该如何处理这样定义的问题的对象设计?无论是在常量、实例变量还是实例方法中,我仍然不确定将该数组存储在何处。请教我怎么做。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-25 06:30:04

上一次我对一个女新手来说是邪恶的。这一次,我会尽量表现得好点。

方法一,使用常量:

代码语言:javascript
复制
A = Class.new

class B < A
  FOO = [ :hello, :world ] # this is your array
end

# Access different constants defined in different descendants is tricky, like this:

class A
  def foo_user
    puts self.class.const_get :FOO
  end
end

B.new.foo_user #=> [ :hello, :world ]

# Note theat you can't do this:

class A
  def foo_user
    puts FOO # this would look for FOO in A mother class only
  end
end

 B.new.foo_user #=> error

方法二,使用属于A的子类的实例变量:

代码语言:javascript
复制
A = Class.new

class B < A
  @foo = [ "hello", "world" ]
end

# This way is more usable. I would go about it like this:

class A
  class << self
    attr_reader :foo     # defining a reader class method
  end

  def foo
    self.class.foo       # delegating foo calls on the instances to the class
  end

  def foo_user
    puts foo
  end
end

B.new.foo_user #=> [ :hello, :world ]

方法三,使用在后代上定义的实例方法:

代码语言:javascript
复制
A = Class.new

class B < A
  def foo
    [ "hello", "world" ]
  end
end

# This way is also usable.

class A
  def foo_user
    puts foo
  end
end

在方法2(属于子类的实例变量)和3(定义在子类上的方法)之间的选择取决于值(数组)的灵活性。方法2最灵活,但方式3所需代码较少。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25479134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档