如何在 Ruby 中获得类似 Java 的效果?
class Outer {
final boolean switch
public Outer(boolean someSwitch) {
switch = someSwitch
}
class Inner {
public void doSomething() {
if (switch) {
//behave like this
} else {
//behave like that
}
}
}
不要介意切换必须是最终的;在 Scala 中则不然。反正。我的内部类位于外部实例的范围内,这就是我喜欢的方式。我不必将开关传递给每个单独的内部实例。
在 Ruby 中,我可以将一个类嵌套在另一个类中,但这并不意味着命名空间之外的任何内容。怎样才能达到我想要的效果呢?我知道这个问题有点模糊,所以即使您不确定,也请随意尝试一下。
最佳答案
Ruby 中没有嵌套类,更多信息 here 。但是 Ruby 非常棒,如果有帮助的话,您可以这样做。
module M
class Outer
attr_accessor :foo
def say_hello()
puts "Hello Outer '#{@foo}'"
Inner.new(self).say_hello()
end
private
class Inner
def initialize(parent)
@parent = parent
end
def say_hello()
puts "Hello Inner '#{@parent.foo}'"
end
end
end
end
instance = M::Outer.new
instance.foo = "foo values"
instance.say_hello
#=> Hello Outer 'foo values'
#=> Hello Inner 'foo values'
关于ruby - 与嵌套类共享作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13413583/