如何在Ruby 1.9中封装一个带有yield的方法

3

我有一个方法,它可以打印出一个编号列表,并通过执行代码块来打印前缀。

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

?


https://repl.it/EKI0 - potashin
1个回答

2

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

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
& 运算符会在可能的情况下将它的操作数转换成一个块(block).
 qwer &Proc.new { |x| x * 2 }
 I am going to call asdf
 4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接