Day12 - the ever-changing variables: class variable, class instance variable and instance variable

Recap:

 

Day 12, to explore details go! Yesterday we talked about broc is the name of the block of memory objects, can store variables; lambda is a method method, strict checks the number of parameters. Today I want to discuss deeper variable :)

 

Ruby classic interview questions # 12

Ruby class variables and class instance variables, variables and entities What's the difference? What is difference between class variable, class instance variable and instance variable?

 

We have discussed the methods and physical methods category at the fourth day ( leafor ).

 

I remember this conclusion under:

 

If you are an entity method, used in a custom entity, you use instance method;

If one method does not variable and a specific entity tied together, use the class method.

Entity variable instance variable

Entity variable is a better conceptual understanding, to give you an example:

I want to run a daily habit RunDaily written in class, in order to continue to maintain good habits, there are two methods: run morning_run morning or evening run evening_run, if you want to run in the morning (morning run), the entity will bring variable @mr parameters 5km, evening (evening) run, then, @ er into the 10km.

 

Today is the 12th day of the ~

 

We create day12 follows:

 

class RunDaily

def morning_run(km)

@mr = km

end

def evening_run(km)

@er = km

end

end

 

day12 = RunDaily.new

p day12.morning_run(5)

p day12

p day12.evening_run(10)

p day12

We can see the physical variables (instance variable) that begin with @, does not need to be declared at the beginning of class, because:

 

Ruby physical variables are not public, only acting on the object to self direct. Except as expressly provided otherwise,

Otherwise it can not be changed or viewed from outside the object. original

 

5

#<RunDaily:0x000055e64755a770 @mr=5>

10

#<RunDaily:0x000055e64755a770 @mr=5,@er=10>

Day12 see this object from the output method is Rundaily, dynamically added two entities and variables mr er.

 

Entity variable attributes (attribute)

Entity variable object is an object attribute (attribute), even with a different class of objects, their properties are different.

 

(Remember we mentioned in the first day of the Ironman Ruby, Ruby worldview, all things are objects do?)

 

I like a saying: Every day is a new day, yesterday, today and tomorrow are different objects, independent of individual :)

 

Let's create a new object, explain the properties of different objects.

 

Suppose I have created this new thing tomorrow (day 13) Day13 encountered vacation days, so in the morning breath ran 21km:

 

day13 = RunDaily.new

p day13.morning_run(21)

p day13

The results show that this object exists in different memory locations, and different variables:

 

21

#<RunDaily:0x0000561a9376e1d0 @mr=21>

Accessor property (attribute accessors)

Just as we sometimes want to know every particular day, respectively, ran several kilometers, or what the article is to re-extract content every day Ironman in the end yes.

 

This time can be read entity variable attributes are very important, so that we can more easily read these different objects (because, who passed will leave marks! Just opened their own written as a diary or Ironman .)

 

Case I: Yesterday

The disclosed method IronmanDairy category to write a property accessor (attribute accessors) Now, let us set (set_dairy), get (get_dairy) Ironman title of the article of yesterday Day12:

 

class IronmanDairy

def set_dairy(title)#write dairy

@title = title

end

 

def get_dairy #read dairy

@title

end

end

 

day11 = IronmanDairy.new

p day11

 

day11.set_dairy(“Explain the difference between block,proc,lamdba.”)

day11.get_dairy # yesterday removed the article title

 

p day11

 

We diary day11 items are read out: show memory locations, and entities @title variables:

 

#<IronmanDairy:0x000055d4f44e2748>

#<IronmanDairy:0x000055d4f44e2748 @title=“Explain the difference between block,proc,lamdba.”>

Case II: Today

set_dairy and get_dairy method, although let's easy to understand how properties are read and write, but to dismantle the details of the code has become too long.

 

In order to produce while having read Read + Write Write function entity variables (in this case, @title), every time to write this set_dairy and get_dairy method, not tired it?

 

(Just like a diary, like, you will not be interpreted as a diary: This is a set of open diary, a diary, and then closed his diary of action.)

 

You just want to. To. write. day. Remember it!

 

There is no streamlined way to do that?

 

(You guessed it!, Ruby Lane usually have a manual method takes a closer look them up!)

 

In order to uphold the spirit of each better than yesterday and today, we propose a modified version:

 

Suppose we want to write a new article on the 12th day day12, you can use the write title = method, and get titlemethod, see the article title, and replace the original set_dairy get_dairy:

 

class IronmanDairy

def title=(title)#write dairy

@title = title

end

 

def title #read dairy

@title

end

end

 


day12 = IronmanDairy.new

day12.title =“class variable,class instance variable and instance variable”

p day12

p day12.title

The results printed:

#<IronmanDairy:0x00005648020c0828>

#<IronmanDairy:0x00005648020c0828 @title=“class variable,class instance variable and instance variable”>

Note, title = here is an entity method, we have to confirm it with .instance_methods:

 

p IronmanDairy.instance_methods(false)#=> [:title=,:title]

Case III: Tomorrow

There did not find the code above, this entity variable @title it appeared in large numbers? If you want to further simplify, you can rewrite attr_accessor way.

 

Suppose we want to create a tomorrow Day13 Ironman article object directly to the property accessor entity attr_accessor: title, assigned to the symbol: title, adding to the beginning of classes in:

 

class IronmanDairy

attr_accessor:title

end

 

day13 = IronmanDairy.new

p day13 #<IronmanDairy:0x00005579aee8bc00>

 

day13.title =“Still thinking…”

p day13 #<IronmanDairy:0x00005579aee8bc00 @title=“Still thinking…”>

 

p day13.title #“Still thinking…”

 

p IronmanDairy.instance_methods(false)#[:title=,:title]

From the above [Yesterday, Today, Tomorrow] three, for example, the wording extracted object attributes represent continuous improvement, is not able to have a comprehensive understanding of the physical variables for it?

 

Category variables class variable

Category variables at the beginning of class, with @@ definition, it is a dangerous thing, because all subcategories changes to the categories of variables, variables will affect the other categories. We use the example of "chicken rabbit with cage," to calculate different animals have several feet:

 

class Animal

@@ legs = nil # preset before the animal's foot is null nil

def self.legs

@@legs

end

end

 

p Animal.legs # => nil

 

class Chicken <Animal # `` chicken category inherit `` animal categories

@@legs = 2

end

p Chicken.legs # => 2

p Animal.legs # => 2 animals get two feet!

 

class Rabbit < Animal

@@legs = 4

end

 

p Rabbit.legs # => 4

p Animal.legs # => 4, the animal has changed four feet!

 


class Snake <Animal # join a snake cage

@@ legs = 0 # snakes do not have feet!

end

 

p Animal.legs # => 0

p Snake.legs # => 0

p Rabbit.legs # => 0 bad, why did not the rabbit foot! ~ ~ ~ ~ Snake was eaten

To solve this problem, we have to study the class instance variables in Ruby to see if there is a better approach.

 

Category entity class instance variable variable

We at the outset to explain the essence of the object-oriented language in the Day1: objects can have variable categories and entities. Since the class is also an object that "class of things," of course, can have "categories of variable entity." We continue to "snake rabbit with cage," an example of, for example three kinds of variables Fuzion:

 

class Animal # Case 1: animal category - class variable

@@ legs = nil # variable is set to nil category

def self.legs

@@legs

end

end

 

p Animal.class_variables # print category variables: @@ legs

p Animal.legs # category variables: the current is null nil

 

p Animal.instance_variables # => [] has not been set physical variables, so nothing to

 

class Animal # Case 2: animal category - instance variable

attr_accessor: legs # entity set variables

@legs = 0

end

 

p Animal.instance_variables # => entity is now able to print variable: @legs

p Animal.legs # still a class variable null nil ( dcjwsc.com )

 

class Animal # Case 3: animal category - class instance variable

class << self;attr_accessor:legs end

#self class in the category, animal category at the current location of the representative (instead of Case 1 and Case 2 yo class of the same name)

 

@legs = 1 # set the "class instance variables" to the default of 1

end

 

p Animal.legs # => 1 # is not nil, is not zero, but 1 (class instance variables!)

 

class Rabbit < Animal

@legs = 4

end

 

p Rabbit.legs # => Rabbit 4 feet

p Animal.legs # => Back to the Category entity variable preset value 1

 


class Snake < Animal

@legs = 0

end

p Snake.legs # => 0 foot snake

p Rabbit.legs # => rabbit or four feet! Great - not to be eaten

p Animal.legs # => Back to the Category entity variable preset value 1

Above examples prove that I actually in the book Effective Ruby Chinese version - 56 found Ruby to write a good program of 48 specific practices Page views: preferring category entity variables, do not use class variables. Category entity variables in addition to breaking the sharing relationship categories and their subcategories (as in our example, the number of foot animal is randomly changed), also offer more packages, so that the definition of the category hierarchy, or from class methods, the only category entity is accessible variables.

 

Finally, a table of comparison and to sum up :)

 

Category class instance variables class variable variable variable class instance variable entity instance variable

@ @@ class variables class instance variables @ variables entities

Attr_accessor rewrite available at the beginning of class set available attr_accessor way to rewrite the way

The method may be used in the category or categories of entities used in the method of the method, the method used is not available in the entity in the entity method

Guess you like

Origin www.cnblogs.com/lannyQ-Q/p/11095418.html