returning struct data as a hash in ruby

后端 未结 4 1535
我在风中等你
我在风中等你 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条回答
  •  生来不讨喜
    2021-02-18 18:39

    I guess I don't know why you'd want to do it either, but:

    s.members.inject({}) { |m, f| m[f] = s[f]; m }
    

    Or, using each_with_object:

    s.members.each_with_object({}) { |m, h| h[m] = s[m] }
    

提交回复
热议问题