我有一个打印出编号列表的方法,产生一个代码块来打印前缀。
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
答案 0 :(得分: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
&
运算符将其操作数转换为块(如果可能)
qwer &Proc.new { |x| x * 2 }
I am going to call asdf
4