Class Methods & Variables
When calling an 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 an instance method is always preceded by a .
,
which is in turn preceded by the object that is calling the method.
Why, then, did this code work in the previous example?
# from inside the Customer class def withdraw_securely(amount, password)
if password == @password
remove_funds(amount)
end
end
Isn’t remove_funds
also an instance method? Why is it suddenly exempt from following the sameobject.
method_being_called
syntax just because it’s inside a method?
This can be compared to spoken language. If you were asking Diego to tell us his name, you might say to him “Diego, tell us your name.”
But if you were asking me to tell you my name, you’d likely say “Tell me your name”.
Yes, you could have said “You, tell me your name,” but that would have been redundant. “You” isimplicit in “Tell me your name”.
Similarly, when you call an instance method from within a class, 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)
end
end
An object can refer to itself using the self
keyword. Think of it as an object’s way of saying “me” or “I”.
When you call remove_funds
from within the Customer
class, you’re saying “remove these funds from myself”.
And since Ruby is all about removing any unnecessary syntax, self
in this context is implicit, and can be left out entirely.
An instance variable like @password
is scoped to a particular instance of a class.
But what if you wanted a variable that was shared across all instances of a class? Almost like… a class variable.
@@check_out_this_cool_class_variable = "boom."
Boom is right.
A class variable’s syntax is twice as cool as an instance variable, because it has two @
’s instead of just one.
Let’s see how one might use a class variable.
class Employee
@@bank = "Udacity International Bank" def bank
@@bank
end
end
Unfortunately, class variables can’t be accessed using attr_accessor
, so you’ll need to create your own bank
getter method in this case.
Initialize two 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 is shared across all instances of an Employee
class.
But… Why?
Class variables are used considerably less frequently than instance variables.
Unlike the public
keyword, though, there are some practical use cases for class variables. Here are two of those use cases.
class Customer
attr_reader :id @@id = 1
@@customers = [] def initialize
@id = @@id
@@id += 1
@@customers << self
end
end
If you break this apart, you’ll see two class variables, @@id
and @@customers
.
Every time a new customer is instantiated, an instance variable of @id
is set to the 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 way, the Customer
class can keep track of the total number of customer objects that have been created.
By assigning the class variable to the instance variable @id
, you are capturing the current ID number from when that particular customer object was created.
Similarly, @@customers
in this case is an Array that holds all the customer objects that have ever been created.
After a new customer is initialized, self
, the particular instance currently being used, is pushed into this @@customers
Array.
Unfortunately, we’re left without an 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 particular customer.
If only there were something else...
Class variables can be especially powerful when coupled with class methods.
Class methods differ from instance methods in that they are called directly on the class name, like so:
Customer.this_is_a_class_method
These are used when you need to call a method that doesn’t apply to a specific instance of a class.
Say you need a method to retrieve all the customers you’ve created so far. This method could be called all
.
Defining a class method works just like defining an instance method, except it must be preceded by self.
class Customer
attr_reader :id @@id = 1
@@customers = [] # ... def initialize
@id = @@id
@@id += 1
@@customers << self
end def self.all
@@customers
end
end
Now, if at any point you’d like to retrieve an 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的更多相关文章
- iOS编码规范
The official raywenderlich.com Objective-C style guide. This style guide outlines the coding con ...
- 微软版的SqlHelper.cs类
一,微软SQLHelper.cs类 中文版: using System; using System.Data; using System.Xml; using System.Data.SqlClien ...
- OracleHelper类
using System; using System.Collections; using System.Collections.Generic; using System.Data; using S ...
- SqlHelper类
using System; using System.Collections; using System.Collections.Generic; using System.Data; using S ...
- 【2016-11-2】【坚持学习】【Day17】【微软 推出的SQLHelper】
从网络上找到 微软原版本的SQLHelper,很多行代码.认真看了,学习了. 代码: using System; using System.Data; using System.Xml; usin ...
- <java基础学习>RE 基础语法(2)
Java Modifiers(java修饰符): Like other languages, it is possible to modify classes, methods, etc., by u ...
- SQLHelper
今天学习了.net后,经过老师的一番讲解,似乎对它越来越渴望了,希望自己在接下来的学习当中,能很好的驾驭.net,加油吧, 下面我分享一个操作SQL数据库的代码大全,谢谢观赏.嘿嘿,还是比较长的哦, ...
- Java Annotation 总结
Annotation 被称为注解,在Java开发中是相当常见的,通过注解,我们可以简化代码提高开发效率.例如Override Annotation,这个应该算是在开发过程中使用最多的注解了.下面这个例 ...
- ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(一) 之 基层数据搭建,让数据活起来(数据获取)
大家好,本篇是接上一篇 ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(零) 前言 ASP.NET SignalR WebIM系列第二篇.本篇会带领大家将 LayIM ...
随机推荐
- Orchard 刨析:Caching
关于Orchard中的Caching组件已经有一些文章做了介绍,为了系列的完整性会再次对Caching组件进行一次介绍. 缓存的使用 在Orchard看到如下一段代码: 可以看到使用缓存的方法Get而 ...
- OpenCart 最新使用教学视频合集
OpenCart 是一个很火的开源电商系统,国内越来越多的人开始使用 OpenCart 搭建自己的电商网站.OpenCart 的功能非常强大,当然功能也非常多.这里整理了 OpenCart 最重要的一 ...
- C# ArcEngine创建内存图层(转载)
C#+Arcengine---创建内存图层 分类:技术文档 2009-12-11 14:43阅读(1498)评论(0) #region 在内存中创建图层 /// <summary& ...
- OneZero第一次会议(非正式)
会议时间:2016年3月20日 15:50~16:50 会议成员:冉华(http://www.cnblogs.com/ranh941/) 张敏(http://www.cnblogs.com/zhang ...
- 为HTML添加图片登录按钮
来源于:http://www.2cto.com/kf/201510/447673.html <!DOCTYPE html> <html> <head lang=" ...
- 【POJ 2886】Who Gets the Most Candies?
题意 约瑟夫问题的升级版,每次出去的是前一个出去的人位置+手上的数字(正往前,负往后).第i个出去的人拿的糖是i的约数的个数.求拿糖最多的人和他的糖果数. 分析 线段树单点更新,反素数. 我竟然WA在 ...
- NOI题库 09:图像旋转翻转变换
NOI题库开始的题,也是略水,当然也是大水,所以彼此彼此 09:图像旋转翻转变换 总时间限制: 1000ms 内存限制: 65536kB 描述 给定m行n列的图像各像素点灰度值,对其依次进行一系列操作 ...
- [NOIP2009] 提高组 洛谷P1071 潜伏者
题目描述 R 国和 S 国正陷入战火之中,双方都互派间谍,潜入对方内部,伺机行动.历尽艰险后,潜伏于 S 国的 R 国间谍小 C 终于摸清了 S 国军用密码的编码规则: 1. S 国军方内部欲发送的原 ...
- linux内存回收 内核参数
ss -atu| awk '/^tcp/{++S[$2]} END {for(a in S) print a,S[a]}' ps up pid (RSS:实际内存大小,长驻内存) ps o pid,c ...
- node-js访问rest api的方法
//npm install node-rest-client --save-dev var Client = require('node-rest-client').Client function l ...