带有默认值的参数哈希的 Ruby 方法:如何 DRY?
我有一个 initialize
方法,它接受哈希值来设置一些实例变量。这基本上就是我想要做的:
class Ad
DEFAULT_PAGE = 'index'.freeze
DEFAULT_CHANNEL = 'general'.freeze
DEFAULT_AREA = 'general'.freeze
attr_accessor :page, :area, :channel
def initialize args={}
@page = args[:page] || DEFAULT_PAGE
@area = args[:area] || DEFAULT_AREA
@channel = args[:channel] || DEFAULT_CHANNEL
end
# ...
end
我看到了一个允许动态设置实例变量的提示,但我不确定如何也包含默认值...
def initialize args={}
args.each do |attr,val|
instance_variable_set("@#{attr}", val) unless val.nil?
end
end
我可以动态引用常量吗?或者有任何更好的方法来做这类事情,欢迎!
...我还意识到 attr_accessor 变量可以单独设置。但我只想这样做。 :)
I have an initialize
method that accepts a hash to set some instance variables. This is basically what I'm trying to do:
class Ad
DEFAULT_PAGE = 'index'.freeze
DEFAULT_CHANNEL = 'general'.freeze
DEFAULT_AREA = 'general'.freeze
attr_accessor :page, :area, :channel
def initialize args={}
@page = args[:page] || DEFAULT_PAGE
@area = args[:area] || DEFAULT_AREA
@channel = args[:channel] || DEFAULT_CHANNEL
end
# ...
end
I saw a tip to allow dynamic setting of instance variables, but I'm not sure how to also include the default values...
def initialize args={}
args.each do |attr,val|
instance_variable_set("@#{attr}", val) unless val.nil?
end
end
Can I refer to a constant dynamically? Or any better ways of doing this sort of thing are welcome!
... I also realize that attr_accessor
variables can be set individually. But I just want to do it like this. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果实例变量位于您的
defaults
哈希中,则此变量也仅创建它们,这样您就不会意外创建/覆盖其他实例变量。我假设您的意思是
除非 val.nil?
:This one also only creates the instance variables if they are in your
defaults
hash, so that you don't accidentally create/overwrite other instance variables.I'm assuming you meant to say
unless val.nil?
:试试这个:
Try this: