【发布时间】:2016-10-31 11:53:45
【问题描述】:
假设我有一个接收字符串和选项哈希的方法。选项哈希以方法名作为键,布尔/值作为值。
some_method("foo", upcase: true, times: 5)
这个方法应该做的是获取字符串,并根据选项哈希对字符串运行某些方法,在这种情况下,它应该使字符串大写,然后将其乘以 5。我们得到 FOOFOOFOOFOOFOO 作为输出。
我遇到的问题是当我使用send 方法时,options 哈希中的一些方法需要参数(例如*,而有些则不需要(例如'upcase')。
这是我目前所拥有的。
def method(string, options = {})
options.each do |method_name, arg|
method_name = :* if method_name == :times
mod_string = mod_string.send(method_name, arg)
end
end
我收到了预期的错误
参数数量错误(给定 1,预期为 0)
(repl):9:in `upcase'
所以,我的问题是:有没有办法只在有参数时发送参数?
我想出的唯一方法是使用 if 语句来检查布尔值
options.each do |method_name, arg|
method_name = :* if method_name == :times
if arg == true
mod_string = mod_string.send(method_name)
elsif !(!!arg == arg)
mod_string = mod_string.send(method_name, arg)
end
end
我只是想看看有没有更好的方法。
【问题讨论】:
标签: ruby