What is the difference between Methods and Attributes in Ruby?

后端 未结 5 509
抹茶落季
抹茶落季 2021-01-31 10:11

Can you give me an example?

5条回答
  •  不思量自难忘°
    2021-01-31 10:47

    Attributes are just a shortcut. If you use attr_accessor to create an attribute, Ruby just declares an instance variable and creates getter and setter methods for you.

    Since you asked for an example:

    class Thing
        attr_accessor :my_property
    
        attr_reader :my_readable_property
    
        attr_writer :my_writable_property
    
        def do_stuff
            # does stuff
        end
    end 
    

    Here's how you'd use the class:

    # Instantiate
    thing = Thing.new
    
    # Call the method do_stuff
    thing.do_stuff
    
    # You can read or write my_property
    thing.my_property = "Whatever"
    puts thing.my_property
    
    # We only have a readable accessor for my_readable_property
    puts thing.my_readable_property 
    
    # And my_writable_propety has only the writable accessor
    thing.my_writable_property = "Whatever"
    

提交回复
热议问题