2

I'm getting this error

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>

when used yield inside another block which is inside a begin statement which is inside a if statement, for a simple understanding here is the prototype

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

The problem is there is no error with the prototype, it worked fine so I dont understand why I'm getting this error, here is my actual code

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

I was testing this code using 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

Any help? regards

4

1 回答 1

2

问题是您正在gen_list递归调用,并且在递归下降的调用站点确实没有阻塞。

你可以做的是:

  • 将块捕获为带有&参数的过程,然后转发它,或者
  • 添加一个块,对递归调用执行另一个 yield

所以...

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
于 2012-07-10T15:26:42.850 回答