returning struct data as a hash in ruby

后端 未结 4 1570
我在风中等你
我在风中等你 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:27

    I don't think the use cases for hashes and structs are very similar. A hash lets you store a variable number of key-value pairs, and is suitable for storing thousands of pairs if a you want. No particular key is guaranteed to be present. With a Struct, you always know what the set of "keys" will be and it is usually small (less than 20).

    Hashes can be used to associate some piece of information with a large number of different objects. Hashes be used to specify optional parameters to a function. Structs can be used when you want to keep some well-defined pieces of information together in one object.

    I've never wanted to convert from the struct to a hash so I'm wondering why you do.

    EDIT 1: Did you know you can use this un-hash-like syntax with Structs?

    P = Struct.new(:x,:y)
    p = P.new(1,2)
    p.x  # => x
    

    EDIT 2: Hashes can also be used to look up objects quickly. obj_hashed_by_name[name] can be much faster than obj_array.find { |a| a.name == name }.

提交回复
热议问题