Ruby:如何将一种方法接收的所有参数和块传递给另一种方法?

mar*_*usM 38 ruby ruby-on-rails

我正在编写一个帮助程序,它将一个HTML属性添加到rails中的link_to标记.所以,我的想法是我的帮助器方法应该接受传递给它的任何参数或块,使用相同的参数调用link_to,将它的属性添加到返回的内容,并将结果返回给调用者.

像这样:

def link_to(*args, &block)
  ... rails code in link_to ...
end

def myhelper(*args, &block) # Notice that at this point, 'args' has already
  link_to()                 # become an array of arguments and 'block' has
  ... my code ...           # already been turned into a Proc.
end

myhelper() # Any arguments or blocks I pass with this call should make
           # it all the way through to link_to.
Run Code Online (Sandbox Code Playgroud)

所以,正如你所看到的,似乎没有办法(不涉及大量的代码和条件分支)将myhelper收到的内容传递给link_to,而没有将所有参数恢复到它们到达之前的状态我的方法.

这个问题是否有更"类似Ruby"的解决方案?

sep*_*p2k 71

您可以使用*&in方法调用将数组转换回参数列表并将其转换回块.所以你可以这样做:

def myhelper(*args, &block)
  link_to(*args, &block)
  # your code
end
Run Code Online (Sandbox Code Playgroud)

  • 这种方法是否适用于Ruby 2.0中的命名参数? (6认同)
  • 我现在觉得很愚蠢:-) 我确定你错了,我正在编写一些示例代码来证明这一点,当然你是对的。谢谢! (2认同)

Mar*_*n13 9

定义方法(...)

Ruby 2.7开始,可以使用 将当前方法的所有参数传递给另一个方法(...)

所以,现在,

def my_helper(*args, &block)
  link_to(*args, &block)
  
  # your code
end
Run Code Online (Sandbox Code Playgroud)

可以改写为

def my_helper(*args, &block)
  link_to(*args, &block)
  
  # your code
end
Run Code Online (Sandbox Code Playgroud)

这是功能请求的链接