【问题标题】:send method: choose when to pass arguments发送方法:选择何时传递参数
【发布时间】: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


    【解决方案1】:

    “当一个方法有一个必需的参数时,调用它”:

    method = mod_string.method(method_name)
    arity = method.arity
    case arity
    when 1, -1
      method.call(arg)
    when 0
      method.call
    else
      raise "Method requires #{arity} arguments"
    end
    

    一个可能更好的方法是重构你的哈希,并准确地给它你想要作为数组传递的参数:

    some_method("foo", upcase: [], times: [5])
    

    那么你可以简单地mod_string.send(method_name, *arg)

    【讨论】:

    • 我刚刚做了arg = [arg].reject { |el| el == true || el == false }mod_string.send(method_name, arg)。它工作得很好。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2021-08-17
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多