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

Struct#to_h

struct.to_h → hash
struct.to_h {|name, value| block } → hash

Returns a Hash containing the names and values for the struct’s members.

If a block is given, the results of the block on each pair of the receiver will be used as pairs.

Example
Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.to_h[:address]   #=> "123 Maple, Anytown NC"
joe.to_h{|name, value| [name.upcase, value.to_s.upcase]}[:ADDRESS]
                     #=> "123 MAPLE, ANYTOWN NC"
See also #to_a #to_json #size #to_s also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1