Skip to content

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

instance method

CSV::Row#to_hash

to_hash

Alias of #to_h

Returns the new Hash formed by adding each header-value pair in self as a key-value pair in the Hash.

Example
source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
row = table[0]
row.to_h # => {"Name"=>"foo", "Value"=>"0"}

Header order is preserved, but repeated headers are ignored:

Example
source = "Name,Name,Name\nFoo,Bar,Baz\n"
table = CSV.parse(source, headers: true)
row = table[0]
row.to_h # => {"Name"=>"Foo"}
See also #to_h #to_s #to_csv #values_at also in 3.3 · 3.2 · 3.1