让我们说我有这样的对象:有条件的关键参数(红宝石2.0)
class Post
def initialize(title: 'title', content: 'content')
@title = title
@content = content
end
end
,但我想补充的逻辑,如:
class Post
def initialize(title: 'title', content: 'content')
@title = title unless title.empty? # if it's empty I'd like to use the default value
@content = content unless content.empty?
end
end
在上面的例子中,我怎么分配关键字参数有条件?
你的问题的essense是否是一个方法(不只是'initialize')可以获取它传递参数的默认值。您可以使用[Kernel#caller](http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-caller)获取调用方法,以及有关[Method @#参数](http://www.ruby-doc.org/core-2.0.0/Method.html#method-i-parameters)。考虑到可以计算默认值并且Ruby没有理由让它们可用于被调用的方法,我非常怀疑是否有办法从被调用的方法中获取它们。然而,.. –
...你可能会看看[merb gem]的'get_args'方法(http://rubydoc.info/github/merb/merb/master/GetArgs)。 –