When is it better to use a Struct rather than a Hash in Ruby?

前端 未结 6 1229
清歌不尽
清歌不尽 2021-01-30 20:44

A Ruby Struct allows an instance to be generated with a set of accessors:

# Create a structure named by its constant
Customer = Struct.new(:name, :address)     #         


        
6条回答
  •  有刺的猬
    2021-01-30 20:57

    A Struct has the feature that you can get at its elements by index as well as by name:

    irb(main):004:0> Person = Struct.new(:name, :age)
    => Person
    irb(main):005:0> p = Person.new("fred", 26)
    => #
    irb(main):006:0> p[0]
    => "fred"
    irb(main):007:0> p[1]
    => 26
    irb(main):008:0> p.name
    => "fred"
    irb(main):009:0> p.age
    => 26

    which sometimes is useful.

提交回复
热议问题