When should I use Struct vs. OpenStruct?

后端 未结 9 1170
孤城傲影
孤城傲影 2020-11-28 00:35

In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use-cases would fit each of these?

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:19

    The use cases for the two are quite different.

    You can think of the Struct class in Ruby 1.9 as an equivalent to the struct declaration in C. In Ruby Struct.new takes a set of field names as arguments and returns a new Class. Similarly, in C, a struct declaration takes a set of fields and allows the programmer to use the new complex type just like he would any built-in type.

    Ruby:

    Newtype = Struct.new(:data1, :data2)
    n = Newtype.new
    

    C:

    typedef struct {
      int data1;
      char data2;
    } newtype;
    
    newtype n;
    

    The OpenStruct class can be compared to an anonymous struct declaration in C. It allows the programmer to create an instance of a complex type.

    Ruby:

    o = OpenStruct.new(data1: 0, data2: 0) 
    o.data1 = 1
    o.data2 = 2
    

    C:

    struct {
      int data1;
      char data2;
    } o;
    
    o.data1 = 1;
    o.data2 = 2;
    

    Here are some common use cases.

    OpenStructs can be used to easily convert hashes to one-off objects which respond to all the hash keys.

    h = { a: 1, b: 2 }
    o = OpenStruct.new(h)
    o.a = 1
    o.b = 2
    

    Structs can be useful for shorthand class definitions.

    class MyClass < Struct.new(:a,:b,:c)
    end
    
    m = MyClass.new
    m.a = 1
    

提交回复
热议问题