Class Methods & Variables

Source: Internet
Author: User

When calling a instance method like withdraw_securely , the syntax generally looks something like this:

object.method_being_called (arguments)

One would therefore think it's safe to assume that's a instance method is always preceded by a . ,

Which is in turn preceded by the object, which is calling the method.

Why, then, does this code work in the previous example?

# From inside the Customer class def withdraw_securely (amount, password)   if password = = @password    remove_funds (amount)  endend

Isn ' t remove_funds also an instance method? Why are it suddenly exempt from following the sameobject.

method_being_calledSyntax just because it ' s inside a method?

This can is compared to spoken language. If you were asking Diego to the US his name, you might say to him "Diego, tell us your name."

But if you were asking me to the tell-me name, you ' d likely say "Tell me your name".

Yes, you could has said "you, tell me your name," and that would has been redundant. "You" isimplicit the "Tell Me your name".

Similarly, when the instance method from within a class, the There is an implicit object being called:itself.

# From inside the Customer class def withdraw_securely (amount, password)   if password = = @password    self.remove_funds (amount)  endend

An object can refer to itself using the self keyword. Think of it as an object ' s a-saying "me" or "I".

When your call remove_funds is from within the Customer class, you ' re saying "remove these funds from myself".

And since Ruby is all about removing any unnecessary syntax, in this self context is implicit, and can being left out Entir Ely.

An instance variable like was @password scoped to a particular instance of a class.

But what if you wanted a variable is shared across all instances of a class? Almost like ... a class variable.

" boom. "

Boom is right.

A class variable ' s syntax is twice as cool as an instance variable, and because it has both @ ' s instead of just one.

Let's see how the one might use a class variable.

class Employee   " Udacity International Bank "  def Bank    @ @bank  endend

Unfortunately, class variables can ' t be accessed using attr_accessor , so you'll need to create your own bank getter method in T His case.

Initialize The instances of an employee to see this working.

Elana = employee.new# = #<employee:0x007fcdb48c19d0>corey = employee.new  #  = = #<employee:0x00nfbdm132ejd9>elana.bank#  = "Udacity International Bank "corey.bank#  =" Udacity International Bank "

Great, now this @@bank class variable are shared across all instances of a Employee class.

But ..... Why?

Class variables is used considerably less frequently than instance variables.

Unlike public the keyword, though, there is some practical use cases for class variables. Here is the those use cases.

class Customer  attr_reader:id  = 1  = []  def  Initialize    = @ @id    + =    1 << self  endend

If you break this apart, you'll see both class variables, and @@id @@customers .

Every time a new customer is instantiated, an instance variable of are set to the @id value of theclass variable @@id .

Immediately Afterwards, the @@id class variable is incremented by one.

Larry = customer.new# = #<customer:0x007faaba8a6aa8 @id =1>christine =  Customer.new#  = #<customer:0x007faaba8a6aa8 @id =2>larry.id# = 1 christine.id # = 2

This is the class can keep track of the total number of Customer customer objects that has been created.

By assigning the class variable to the instance variable @id , you is capturing the current ID number from when this par Ticular Customer object was created.

Similarly, in this case is a Array that holds all the @@customers customer objects that has ever been created.

After a new customer was initialized, self the particular instance currently being used, is the pushed to this @@customers Array.

Unfortunately, we ' re left without a appropriate interface for accessing @@customers .

It wouldn ' t make sense to create a customers instance method, since an Array of customers isn ' t really a property of a Particu Lar customer.

If only there were something else ...

Class variables can especially powerful when coupled with class methods.

Class methods differ from instance methods in that they is called directly on the class name, like so:

Customer.this_is_a_class_method

These is used when you need to call a method, the doesn ' t apply to a specific instance of a class.

Say need a method to retrieve all the customers you ' ve created so far. This method could is called all .

Defining a class method works just like defining an instance method, except it must is preceded byself.

class Customer  attr_reader:id  = 1  = []  #  ...  def Initialize     = @ @id    + =    1 << self  end  def  Self.all    @ @customers  endend

Now, if at any of the retrieve a Array of all existing customers, you can simply call the class method.

Customer.all # = = [#<customer:0x007faaba84c148 @id =1>, #<customer:0x007faaba82fe30 @id =2>]

Class Methods & Variables

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.