Ruby Class vs Struct

后端 未结 5 882
滥情空心
滥情空心 2021-02-02 08:48

I have seen codebases using Structs to wrap around attributes and behavior inside a class. What is the difference between a Ruby Class and a Struct? And when should one be used

5条回答
  •  不要未来只要你来
    2021-02-02 09:29

    From the Struct docs:

    A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.

    The Struct class generates new subclasses that hold a set of members and their values. For each member a reader and writer method is created similar to Module#attr_accessor.

    So, if I want a Person class that I can access a name attribute (read and write), I either do it by declaring a class:

    class Person
      attr_accessor :name
    
      def initalize(name)
        @name = name
      end
    end
    

    or using Struct:

    Person = Struct.new(:name)
    

    In both cases I can run the following code:

     person = Person.new
     person.name = "Name"
     #or Person.new("Name")
     puts person.name
    

    When use it?

    As the description states we use Structs when we need a group of accessible attributes without having to write an explicit class.

    For example I want a point variable to hold X and Y values:

    point = Struct.new(:x, :y).new(20,30)
    point.x #=> 20
    

    Some more examples:

    • http://blog.steveklabnik.com/posts/2012-09-01-random-ruby-tricks--struct-new
    • "When to use Struct instead of Hash in Ruby?" also has some very good points (comparing to the use of hash).

提交回复
热议问题