如果你真的只是想美化这种东西,为什么不将所有方法包装在一个类中,如下所示:
# a container to store all your methods you want to use a hash to access
class MethodHash
alias [] send
def one
puts "I'm one"
end
def two
puts "I'm two"
end
end
x = MethodHash.new
x[:one] # prints "I'm one"
x.two # prints "I'm one"
或者,使用您的示例:
# a general purpose object that transforms a hash into calls on methods of some given object
class DelegateHash
def initialize(target, method_hash)
@target = target
@method_hash = method_hash.dup
end
def [](k)
@target.send(@method_hash[k])
end
end
class A
def initialize
@a = DelegateHash.new(self, { 0 => :a })
end
def a()
puts "hello world"
end
def b()
@a[0]
end
end
x = A.new
x.a #=> prints "hello world"
x.b #=> prints "hello world"
您犯的另一个基本错误是您@a
在任何实例方法之外进行了初始化 - 只是在A
. 这是一个很大的禁忌,因为它不起作用。请记住,在 ruby 中,一切都是对象,包括类,@
前缀表示任何对象的实例变量当前是 self。在一个实例方法定义里面,self
是一个类的实例。但除此之外,就在类定义内部,是类对象 - 所以你定义了一个以类 objectself
命名的实例变量,没有一个实例可以直接访问。@a
A
A
Ruby 确实有这种行为的原因(如果您知道自己在做什么,类实例变量会非常方便),但这是一种更高级的技术。
简而言之,只在initialize
方法中初始化实例变量。