1

私は Jekyll のソースコードを調べていて、この方法に出くわしました:

  # Public: Generate a Jekyll configuration Hash by merging the default
  # options with anything in _config.yml, and adding the given options on top.
  #
  # override - A Hash of config directives that override any options in both
  #            the defaults and the config file. See Jekyll::DEFAULTS for a
  #            list of option names and their defaults.
  #
  # Returns the final configuration Hash.
  def self.configuration(override)
    # Convert any symbol keys to strings and remove the old key/values
    override = override.reduce({}) { |hsh,(k,v)| hsh.merge(k.to_s => v) }

    # _config.yml may override default source location, but until
    # then, we need to know where to look for _config.yml
    source = override['source'] || Jekyll::DEFAULTS['source']

    # Get configuration from <source>/_config.yml or <source>/<config_file>
    config_file = override.delete('config')
    config_file = File.join(source, "_config.yml") if config_file.to_s.empty?

    begin
      config = YAML.safe_load_file(config_file)
      raise "Configuration file: (INVALID) #{config_file}" if !config.is_a?(Hash)
      $stdout.puts "Configuration file: #{config_file}"
    rescue SystemCallError
      # Errno:ENOENT = file not found
      $stderr.puts "Configuration file: none"
      config = {}
    rescue => err
      $stderr.puts "           " +
                   "WARNING: Error reading configuration. " +
                   "Using defaults (and options)."
      $stderr.puts "#{err}"
      config = {}
    end

    # Merge DEFAULTS < _config.yml < override
    Jekyll::DEFAULTS.deep_merge(config).deep_merge(override)
  end
end

コメントにもかかわらず、それが何をするのかわかりません。reduce({})特に私を悩ませます - それは何をしますか?

また、直前に呼び出されるメソッドconfigurationは次のとおりです。

options = normalize_options(options.__hash__) 

何をし__hash__ますか?

4

2 に答える 2

0

reduce多くの場合、配列またはハッシュを構築するために使用されます。これは、mapまたはを使用するのと同様の方法でcollect、通常は要素への何らかの操作の後に、各要素をそのコンテナーに繰り返し追加することによって行われます。

each_with_objectそのような操作ではより直感的であるため、代わりに使用します。

[:foo, :bar].each_with_object({}) do |e, h|
  h[e.to_s] = e
end

each_with_objectのようにブロックから返された「記憶された」値を持つ必要がないことに注意してくださいreduceまたはinject望んでいます。reduceとはいえ、機能しないinject他のタイプの合計マジックには最適なので、それらもツールボックスに残しておいてください。each_with_object

于 2013-04-01T15:41:56.707 に答える