1

我是 Ruby 的初学者,无法理解这段代码

    require_relative 'custom_page'

module Jekyll   
  class Tag < CustomPage
    def initialize(site, base, dir, tag)
      super site, base, dir, 'tag'

      self.data['tag'] = tag
      self.data['title'] = "#{site.config['tag_title_prefix'] || 'Tag: '}#{tag}"
      self.data['description'] = "#{site.config['tag_meta_description_prefix'] || 'Tag: '}#{tag}"
    end
  end

  class Tags < CustomPage
    def initialize(site, base, dir)
      super site, base, dir, 'tags'
      self.data['tags'] = site.categories.keys.sort
      #1# puts self.data['tags']
    end
  end

  class Site
    # generate_tags_categories is called by the custom process function in site_process.rb

    def generate_tags_categories            
      dir = self.config['tag_dir'] || 'tags'
      write_page Tags.new(self, self.source, dir) if self.layouts.key? 'tags'        

      self.categories.keys.each do |tag|
      puts "dd"
      #2# puts tag    
      write_page Tag.new(self, self.source, File.join(dir, tag.slugize), tag)
      end
    end
  end
end

在上面的代码中,语句puts self.data['tags'](标记为 1)按预期输出了 10 多个值。但是,行puts tag(标记为 2)仅输出一个值,这意味着该数组仅包含一个值。不应self.categories.keys.each循环遍历本身分配给的所有值self.data['tags']

4

1 回答 1

2

您可以先确保“类别”在进入循环之前仍然包含许多值:

puts "categories.keys: #{self.categories.keys.inspect}" # <<- here
self.categories.keys.each do |tag|
  puts "dd"
  #2# puts tag

如果第一个puts向您显示多个值,并且循环仅被调用一次,那么您可能需要调查可能导致循环中断的原因。也许write_page会抛出异常,赶上调用堆栈的某个地方?

调试某些值时,最好使用inspectmethod 而不是(由 自动调用puts) method to_s。的输出对inspect调试更友好。

“标签”有可能(但不太可能)包含一些清除先前输出的控制字符或类似的东西。inspect总是安全的。(好吧,并非总是如此,但在大多数情况下;)

于 2011-09-07T08:44:34.963 回答