如何在Ruby中实现选项哈希? [英] How to implement options hashes in Ruby?
本文介绍了如何在Ruby中实现选项哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何实现选项哈希?一个具有选项散列的类的结构如何?假设我有一个人课程。我想实现一个方法,比如my_age,当被调用时会使用选项哈希来告诉我我的年龄。
How can I implement options hashes? How is the structure of a class that has option hashes in it? Say I have a person class. I want to implement a method such as my_age that when called upon will tell me my age using options hashes.
推荐答案
您可以这样做:
You could do something like this:
class Person
def initialize(opts = {})
@options = opts
end
def my_age
return @options[:age] if @options.has_key?(:age)
end
end
现在你可以打电话到这样的年龄了
and now you're able to call to the age like this
p1 = Person.new(:age => 24)<br/>
p2 = Person.new
p1.my_age # => 24<br/>
p2.my_age # => nil
这篇关于如何在Ruby中实现选项哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文