我收到此错误
LocalJumpError: no block given (yield)
from fops.rb:52:in `block (2 levels) in gen_list'
from /home/phanindra/.gem/ruby/1.9.1/gems/mp3info-0.6.18/lib/mp3info.rb:306:in `open'
from fops.rb:51:in `block in gen_list'
from fops.rb:46:in `each'
from fops.rb:46:in `gen_list'
from fops.rb:48:in `block in gen_list'
from fops.rb:46:in `each'
from fops.rb:46:in `gen_list'
from fops.rb:48:in `block in gen_list'
from fops.rb:46:in `each'
from fops.rb:46:in `gen_list'
from fops.rb:48:in `block in gen_list'
from fops.rb:46:in `each'
from fops.rb:46:in `gen_list'
from (irb):2
from /usr/bin/irb:12:in `<main>
当在if语句中的begin语句内的另一个块内使用yield时, 这里简单的理解是原型
def test
if 1 then
begin
test2(5) do |x|
yield x
end
rescue
end
end
end
def test2(n)
n.times do |k|
yield k
end
end
test() do |y|
puts y
end
问题是原型没有错误,它工作正常所以我不明白为什么我收到此错误,这是我的实际代码
require "mp3info"
module MusicTab
module FOps
def self.gen_list(dir)
prev_pwd=Dir.pwd
begin
Dir.chdir(dir)
rescue Errno::EACCES
end
Dir[Dir.pwd+'/*'].each{|x|
if File.directory?(x) then
self.gen_list(x)
else
begin
Mp3Info.open(x) do |y|
yield "#{y.tag.title},#{y.tag.album},#{y.tag.artist},#{x}"
end
rescue Mp3InfoError
end
end
}
Dir.chdir(prev_pwd)
end
end
end
我正在使用irb
测试此代码[phanindra@pahnin musictab]$ irb
irb(main):001:0> load 'fops.rb'
/usr/share/rubygems/rubygems/custom_require.rb:36:in `require': iconv will be deprecated in the future, use String#encode instead.
=> true
irb(main):002:0> MusicTab::FOps.gen_list('/fun/Music') do |l|
irb(main):003:1* puts l
irb(main):004:1> end
有任何帮助吗? 问候
答案 0 :(得分:1)
问题是你是递归地调用gen_list
而在调用网站上进行递归下降确实没有阻塞。
你可以做的是:
&
参数将该块捕获为proc,然后将其转发,或 因此...
def f1 x, &block
block.call(x)
if x > 0
f1 x - 1, &block
end
end
# ...or...
def f2 x
yield x
if x > 0
f2 x - 1 do |y|
yield y
end
end
end
f1 2 do |q|
p ['b1', q]
end
f2 2 do |q|
p ['b2', q]
end