returning struct data as a hash in ruby

后端 未结 4 1557
我在风中等你
我在风中等你 2021-02-18 18:05

Is there a valid reason for there not being a method to return the data of a standard ruby struct as a hash (member, value pairs)? Seeing that structs and hashes have very simil

4条回答
  •  梦毁少年i
    2021-02-18 18:28

    (Ruby <= 1.9.3) OpenStruct has OpenStruct#marshall_dump and Struct has Struct#each_pair (use to_a to get the pairs and Hash+to_a to get the hash):

    Person = Struct.new(:name, :age)
    person = Person.new("Jamie", 23)
    person_hash = Hash[person.each_pair.to_a]
    #=> {:age=>23, :name=>"Jamie"}
    

    With Ruby 2.0 things are easier: Struct#to_h, OpenStruct#to_h:

    Person = Struct.new(:name, :age)
    person = Person.new("Jamie", 23)
    person_hash = person.to_h
    #=> {:age=>23, :name=>"Jamie"}
    

提交回复
热议问题