Ruby Learning: Class definitions and instance variables

Source: Internet
Author: User



Ruby is completely object-oriented, all data is objects, there is no independent method outside the class, all methods are defined in the class.



I. Definition syntax for classes



The definition of a class begins with the Class keyword, followed by the name of the classes, ending with an end identifier.



The methods in the class begin with the DEF keyword, followed by the method name and the argument list (if any), ending with an end identifier.



The class also has constructors, and the name must be initialize.



Objects are created through new, and new is the method of the class.



Examples are as follows:


class Demo
     def initialize
         puts "begin create object"
     end
    
     def test
         puts "test"
     end
end

#Create object, call the method of the object
demo1 = Demo.new
demo1.test 


The above code first defines a class demo, which defines two sub-methods, both of which have no parameters.
It then creates an object with new, assigns a value to the variable demo1, and finally calls the class's Test method.



The output information for the above code run is:



Begin Create Object
Test



Member variables in class II



There are three kinds of variables in the class



1, one is a local variable, within the method and the parameters of the method. This is the normal identifier definition.



2. Instance variables of the class. This definition differs from other languages and needs to be identified by the @ symbol. cannot be accessed directly through an object, but is accessed through a method, equivalent to a private member in Java.



3. Class variables, which belong to class level, are shared for all objects of the class and need to be identified by the @@ symbol






Instance variables of Class III



Let's look at an example of an instance variable of a class:


class Demo
     def initialize (value)
         @a = value
     end
    
     def getA
         return @a
     end
    
     def setA (value)
         @ a = value
     end
end

#Create object, call the method of the object
demo1 = Demo.new (2)
puts demo1.getA
demo1.setA (10)
puts demo1.getA 


The demo class created in the above code defines and initializes an instance variable @a in the constructor, and defines the get and set methods to access the instance variables.
In Ruby, instance variables cannot be accessed directly outside the class, such as puts [email protected], which would report a syntax error.



For instance variables, this is verbose and cumbersome if you need to define the appropriate get and set methods each time, and you can access them externally through the get and set methods.



Ruby simplifies these operations by using its meta-programming features. Let's take a look at the sample code:


class Demo
     attr_accessor: a
    
     def initialize (value)
         @ a = value
     end
end

#Create object, call the method of the object
demo1 = Demo.new (2)
puts demo1.a
demo1.a = 10
puts demo1.a 


The above code defines an instance variable @a through attr_accessor:a and initializes it in the constructor.
The difference with the above is that the external can be accessed directly from the object variable, but not the @ symbol, but access within the method of the class requires the @ symbol.



As you can see, this approach eliminates the definition of get and set methods, which is more concise to access.



setting Attr_accessor automatically sets the instance variable (@a in the example above) , create the set and get methods.




class Demo
     attr_reader: a
    
     def initialize (value)
         @ a = value
     end
    
     def set (value)
         @a = value
         puts @a
     end
end

#Create object, call the method of the object
demo1 = Demo.new (2)
demo1.set (10)
puts demo1.a 


If defined as Attr_reader, the variable information can only be read demo1.a outside the class, but not demo1.a = 2 (because this is actually called the set method, and Attr_reader does not produce a set method). Note that this only affects external access, and the internal methods of the class use no relationship.


class Demo
     attr_writer: a
    
     def initialize (value)
         @ a = value
     end
    
     def set (value)
         @a = value
         puts @a
     end
    
     def print
         puts @a
     end
end

#Create object, call the method of the object
demo1 = Demo.new (2)
demo1.a = 20
demo1.print 


As can be seen from the above example, defined as Attr_writer mode, can only be assigned to the outside of the class, cannot read (if the puts demo1.a here will report a syntax error.) ).
Internal access to the same class is not affected.



It is necessary to note that an instance variable of a class does not have to be defined and initialized in the constructor first. It can be defined and used in any method of the class, and it does not need to be initialized before it is used.



As in the following code:


class Demo
     def set (value)
         @a = value
     end
    
     def print
         puts @a
     end
end

#Create object, call the method of the object
demo1 = Demo.new
demo1.print
demo1.set (10)
demo1.print 


If the instance variable is referenced before initialization, the value is nil (similar to null in Java). As in the code above, the Print method is called directly after the object is created, the @a is referenced in the Print method, and before that @a is not defined and initialized, this does not give an error, except that the value of @a is nil.



As you can see, compared to traditional languages such as Java, C + +, the operation of instance variables of classes in Ruby is more flexible and clearer.






Ruby Learning: Class definitions and instance variables


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.