Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

ENV.to_h

ENV.to_h → hash of name/value pairs
ENV.to_h {|name, value| block } → hash of name/value pairs

With no block, returns a Hash containing all name/value pairs from ENV:

Example
ENV.replace('foo' => '0', 'bar' => '1')
ENV.to_h # => {"bar"=>"1", "foo"=>"0"}

With a block, returns a Hash whose items are determined by the block. Each name/value pair in ENV is yielded to the block. The block must return a 2-element Array (name/value pair) that is added to the return Hash as a key and value:

Example
ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}

Raises an exception if the block does not return an Array:

Example
ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))

Raises an exception if the block returns an Array of the wrong size:

Example
ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
See also .to_a .to_hash .store .to_s also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0