如何包装在 Ruby 1.9 中产生的方法

How to wrap a method that yields in Ruby 1.9

我有一个打印编号列表的方法,让代码块打印前缀。

arr = %w(a b c)

def print_lines(array)
  array.each_with_index do |item, index|
    prefix = yield index
    puts "#{prefix} #{item}"
  end
end

print_lines(arr) do |index|
  "(#{index})"
end

这会产生以下输出:

(0) a
(1) b
(2) c

现在我想用另一个方法包装 print_lines 并调用它。

def print_lines_wrapped(array)
  puts 'print_lines_wrapped'
  print_lines(array)
end

print_lines_wrapped(arr) do |index|
  "(#{index})"
end

然而,这给了我一个 LocalJumpError

test_yield.rb:5:in `block in print_lines': no block given (yield) (LocalJumpError)
  from test_yield.rb:4:in `each'
  from test_yield.rb:4:in `each_with_index'
  from test_yield.rb:4:in `print_lines'
  from test_yield.rb:16:in `print_lines_wrapped'
  from test_yield.rb:19:in `<main>'

为什么我得到 LocalJumpError

如何实现 print_lines_wrapped 以便我可以这样调用它:

print_lines_wrapped(arr) do |index|
  "(#{index})"
end

并获得以下输出:

print_lines_wrapped
(0) a
(1) b
(2) c

?

您的包装方法还必须接受一个块并将其传递给包装方法。没有隐式传递块:

def print_lines_wrapped(array, &block)
  puts 'print_lines_wrapped'
  print_lines(array, &block)
end

示例:

def asdf(&block) puts yield(2) end
def qwer(&block)
  puts "I am going to call asdf"
  asdf &block
end

asdf { |x| x * 3 }
6
=> nil
qwer { |x| x * 5 }
I am going to call asdf
10
=> nil

如果可能,& 运算符将其操作数转换为块

 qwer &Proc.new { |x| x * 2 }
 I am going to call asdf
 4