gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:47 26 4
gpt4 key购买 nike

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

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

?

最佳答案

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

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

关于ruby - 如何包装在 Ruby 1.9 中产生的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com