title: Ruby Net::HTTP passing headers through the creation of request
body: <p>Maybe I'm just blind but many post about passing headers in Net::HTTP follows the lines of </p>
  
  <pre><code>require 'net/http'    
  
  uri = URI("http://www.ruby-lang.org")
  req = Net::HTTP::Get.new(uri)
  req['some_header'] = "some_val"
  
  res = Net::HTTP.start(uri.hostname, uri.port) {|http|
    http.request(req)
  }
  
  puts res.body
  </code></pre>
  
  <p>(From <a href="https://stackoverflow.com/questions/44839503/ruby-send-get-request-with-headers">Ruby - Send GET request with headers</a> metaphori's answer)</p>
  
  <p>And from the Net::HTTP docs (<a href="https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html" rel="nofollow noreferrer">https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html</a>)</p>
  
  <pre><code>uri = URI('http://example.com/cached_response')
  file = File.stat 'cached_response'
  
  req = Net::HTTP::Get.new(uri)
  req['If-Modified-Since'] = file.mtime.rfc2822
  
  res = Net::HTTP.start(uri.hostname, uri.port) {|http|
    http.request(req)
  }
  
  open 'cached_response', 'w' do |io|
    io.write res.body
  end if res.is_a?(Net::HTTPSuccess)
  </code></pre>
  
  <p>But what is the advantage of doing the above when you can pass the headers via the following way?</p>
  
  <pre><code>options = { 
    'headers' =&gt; {
      'Content-Type' =&gt; 'application/json'
    }
  }
  
  request = Net::HTTP::Get.new('http://www.stackoverflow.com/', options['headers'])
  </code></pre>
  
  <p>This allows you to parameterize the headers and can allow for multiple headers very easily. </p>
  
  <p>My main question is, what is the advantage of passing the headers in the creation of Net::HTTP::Get vs passing them after the creation of Net::HTTP::Get</p>
  
  <p>Net::HTTPHeader already goes ahead and assigns the headers in the function</p>
  
  <pre><code>def initialize_http_header(initheader)
      @header = {}
      return unless initheader
      initheader.each do |key, value|
        warn "net/http: duplicated HTTP header: #{key}", uplevel: 1 if key?(key) and $VERBOSE
        if value.nil?
          warn "net/http: nil HTTP header: #{key}", uplevel: 1 if $VERBOSE
        else
          value = value.strip # raise error for invalid byte sequences
          if value.count("\r\n") &gt; 0
            raise ArgumentError, 'header field value cannot include CR/LF'
          end
          @header[key.downcase] = [value]
        end
      end
    end
  </code></pre>
  
  <p>So doing 
  <code>request['some_header'] = "some_val"</code> almost seems like code duplication. </p>