class variables and class instance variables in Ruby

Source: Internet
Author: User
Tags inheritance

First, in ruby1.8, class variables are shared by all subclasses and parent classes, and you can look at the following code:

class IntelligentLife
 @@home_planet = nil

 def  self.home_planet
  @@home_planet
 end
 def self.home_planet=(x)
   @@home_planet = x
 end
 #... 
end
class Terran < IntelligentLife
 @@home_planet = "Earth"
end

class Martian < IntelligentLife
  @@home_planet = "Mars"
end

p IntelligentLife.home_planet
p  Terran.home_planet
p Martian.home_planet

You can see that the results are the same. This is because the class variables of the parent class are shared by the entire inheritance system.

Here, if we want to get the results we need, we're going to use class instance variables, because class instance variables are strictly per-class. Rather than being shared by the entire inheritance system.

class IntelligentLife
 @home_planet = nil

 class << self
  attr_accessor :home_planet
 end
end
class Terran < IntelligentLife
 @home_planet = "Earth"
end

class Martian < IntelligentLife
  @home_planet = "Mars"
end

p IntelligentLife.home_planet
p  Terran.home_planet
p Martian.home_planet

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.