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
lib/net/http/header.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/lib/net/http/header.rb, line 359
def fetch(key, *args, &block) #:yield: +key+
a = @header.fetch(key.downcase.to_s, *args, &block)
a.kind_of?(Array) ? a.join(', ') : a
end
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.