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 publickeyword, 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 ...
随机推荐
- SEO入门教程
什么是SEO? SEO的中文名叫做搜索引擎优化,主要的作用是将网站的关键词优化到搜索引擎靠前的位置 其中关键词可以划分成以下这几类: 主关键词,长尾关键词,相关关键词 例如:主关键词:网页 长尾关键词 ...
- ModernUI教程:第一个ModernUI应用(采用项目模板)
在我们开始之前,请确保你已经为你的Visual2012或者2013安装了ModernUI for WPF的模板扩展: >>从Visual Studio 库 下载并安装VSIX扩展 > ...
- [BZOJ1801][AHOI2009]中国象棋(递推)
题目:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1801 分析: 只会50的状态压缩…… 然后搜了下题解,发现是dp 首先易得每行每列至多 ...
- 传智168期JavaEE就业班 day03-js
* 课程回顾: * CSS * CSS的简介 * 层叠样式表. * CSS与HTML的结合(4种) * HTML的标签提供了属性 style="CSS的代码" * HTML提供了标 ...
- log4net将日志进行分类,保存到不同的目录当中
1.新建Logs的Class类:代码如下: public class ApiLogs { public static int Log_Level { get; set; } private stati ...
- RegexBuddy正则表达式工具
RegexBuddy非常的好用,而且还能生成.net的代码. 我们在使用正则匹配时,毕竟.net提供的方法中,对于多行匹配就不能用单纯的正则去实现,而我们需要把它转换成相应的类库方法进行实现. 那么R ...
- MAC OS下安装Erlang
这是个很大的问题,也是个很小的问题,恩.因为我最终解决方案是用了别人写的工具,名叫erlbrew: https://github.com/mrallen1/erlbrew 按照页面上的指导安装使用即可 ...
- IQ测试
1.4个人过桥,只能两两过桥,且只有一盏灯,必须有灯才能过桥,4个人过桥时间分别为1,2,5,10分钟,最短多少时间可以过桥? 答案:1和2先走,1再返回,花3分钟.5和10走,2回去,花了3+10+ ...
- iOS应用开发最佳实践系列一:编写高质量的Objective-C代码
本文由海水的味道编译整理,转载请注明译者和出处,请勿用于商业用途! 点标记语法 属性和幂等方法(多次调用和一次调用返回的结果相同)使用点标记语法访问,其他的情况使用方括号标记语法. 良好的 ...
- js div浮动层拖拽效果代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...