Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Net::HTTPHeader#fetch

(::interned key) -> ::String
(::interned key, untyped) -> untyped
(::interned key) { (::String) -> untyped } -> untyped
fetch(key, default_val = nil) {|key| ... } → object
fetch(key, default_val = nil) → value or default_val

With a block, returns the string value for key if it exists; otherwise returns the value of the block; ignores the default_val; see Fields:

Example
res = Net::HTTP.get_response(hostname, '/todos/1')

# Field exists; block not called.
res.fetch('Connection') do |value|
  fail 'Cannot happen'
end # => "keep-alive"

# Field does not exist; block called.
res.fetch('Nosuch') do |value|
  value.downcase
end # => "nosuch"

With no block, returns the string value for key if it exists; otherwise, returns default_val if it was given; otherwise raises an exception:

Example
res.fetch('Connection', 'Foo') # => "keep-alive"
res.fetch('Nosuch', 'Foo')     # => "Foo"
res.fetch('Nosuch')            # Raises KeyError.
See also #each_value #form_data= #each_name #get_fields also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0