如何使用哈希键作为类的方法? [英] How do I use hash keys as methods on a class?
问题描述
我有一个课程和一个哈希.如何让hash的成员动态成为类上以key为方法名的方法?
I have a class and a hash. How can I get the members of the hash to dynamically become methods on the class with the key as the method name?
class User
def initialize
@attributes = {"sn" => "Doe", "givenName" => "John"}
end
end
例如,我希望能够有以下输出 Doe
:
For example, I would like to be able to have the following output Doe
:
u = User.new
puts u.sn
推荐答案
def method_missing(name, *args, &blk)
if args.empty? && blk.nil? && @attributes.has_key?(name)
@attributes[name]
else
super
end
end
说明:如果你调用一个不存在的方法,method_missing 将被调用,方法名作为第一个参数,后跟提供给方法的参数和块(如果有的话).
Explanation: If you call a method, which does not exist, method_missing is invoked with the name of the method as the first parameter, followed by the arguments given to the method and the block if one was given.
在上面我们说如果一个没有定义的方法被调用时没有参数也没有块,并且散列中有一个以方法名称作为键的条目,它将返回该条目的值.否则它会照常进行.
In the above we say that if a method, which was not defined, is called without arguments and without a block and the hash has an entry with the method name as key, it will return the value of that entry. Otherwise it will just proceed as usual.
这篇关于如何使用哈希键作为类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!