What is the difference between Methods and Attributes in Ruby?

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

Can you give me an example?

5条回答
  •  旧时难觅i
    2021-01-31 10:49

    Attributes are, strictly speaking, the instance variables of a class instance. In more general terms, attributes are usually declared using the attr_X type methods, while methods are simply declared as is.

    A simple example might be:

    attr_accessor :name
    attr_reader :access_level
    
    # Method
    def truncate_name!
      @name = truncated_name
    end
    
    # Accessor-like method
    def truncated_name
      @name and @name[0,14]
    end
    
    # Mutator-like method
    def access_level=(value)
      @access_level = value && value.to_sym
    end
    

    The distinction between these two is somewhat arbitrary in Ruby since no direct access to them is specifically provided. This contrasts quite strongly with other languages such as C, or C++ and Java where access of an objects properties and calling methods is done through two different mechanisms. Java in particular has accessor/mutator methods that are spelled out as such, whereas in Ruby these are implied by name.

    It is often the case, as in the example, where the difference between an "attribute accessor" and a utility method that provides data based on an attribute's value, such as truncated_name, is minor.

提交回复
热议问题