使用带有参数的proc速记

时间:2018-07-27 21:00:11

标签: ruby

是否有一种方法可以为块参数以及常规参数提供与符号的语法快捷方式?一个具体的例子:

def ewa_test(x, o)
  if o.include? x
    o << "more #{x}"
  else
    o << x
  end
end

fridge_contents = %w( pepperoni green_onions mushrooms olives chives )

# shortcut for calling upcase on every element
# returns ["PEPPERONI", "GREEN_ONIONS", "MUSHROOMS", "OLIVES", "CHIVES"]
fridge_contents.map(&:upcase)

# same shortcut to call ewa_test on every element
fridge_contents.each_with_object([]) { |x, o| ewa_test(x, o) }

# obviously without an object argument, each_with_object raises ArgumentError
fridge_contents.each_with_object(&:ewa_test)

# each raises NoMethodError: private method `ewa_test' called for "pepperoni":String
fridge_contents.each_with_object([], &:ewa_test)

# syntax error
fridge_contents.each_with_object(&:ewa_test, [])

1 个答案:

答案 0 :(得分:4)

您在这里的路线正确,但请记住,&:x表示的含义是特定于迭代器的,例如map

a.map(&:x)

等效于:

a.map { |o| o.send(:x) }

等同于:

a.map { |o| o.x }

没有提供多个参数的规定。在您的情况下,您需要这样做:

fridge_contents.each_with_object([], &method(:ewa_test))

method(:x)处返回一种调用非特定于对象的方法的方法。