Ruby uses a short piece of code to test your reference type skill

Source: Internet
Author: User
Class fixnum attr_accessor: valueendx = 1 p x. object_idx.value = "anleb" P x. value. object_iddef change (x) P x. object_id p x. value. object_id x = 2 # pointer change X. value = "mr. W "P x. object_id p x. value. object_id # x pointer changed here GC recycles endchange xp x. valuep X. object_idp X. value. object_id print 3229503603229503605229502901 "anleb" 322950360

This sectionCodeWell, this is the case where we can't change the value passed in a common method. Not to mention it, we all know that the internal variables of the method change the pointer and exit the method, the pointer is destroyed, and X returns to the top-level domain X, which is the original pointer.

Now, why does the # x = 2 comment out and the result change? The problem lies in attr_accessor: value.
This code is equivalent:

 
Def value = (value) @ value = value end def value @ value end

Note that no, the returned value is @ value, so the value in the object will be modified. I don't know if it's true or not.

Class fixnum attr_accessor: value end x = 1 p x. object_id X. value = "anleb" P x. value. object_id def change (x) P x. object_id p x. value. object_id # x = 2 X. value = "mr. W "P x. object_id p x. value. object_id end change x P x. value p x. object_id p x. value. object_id # result: 3 5875824 3 5875824 3 5875704 1 "mr. W "3 5875704

We have done everything we can about whether the value or reference passed in this method on the Forum. Here we will not talk about the basics.
Check the Code. If # x = 2 is not commented, the result of the Code is as follows:

 

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.