Last active
October 27, 2017 10:38
-
-
Save mygoare/261c89c4315f0f213f08e238da6caf0d to your computer and use it in GitHub Desktop.
ruby 类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ruby是完全面向对象的,即使对于某个实际的类也是如此。ruby的任何类,比如Array,或者是任何自己定义的类,都是Class类的实例。 | |
所以,类的静态方法,相当于这个类(或者是Class类的对象)的singleton_methods.也就是说,ruby本质是没有静态方法的。 | |
# ruby 常量,实例变量,类变量,实例方法,类方法(类作为Ruby Class类的实例对象的 单例方法) | |
class Counter | |
DESC = "It is a counter" | |
@@num = 0 | |
def initialize name, num | |
@name = name | |
@num = num | |
end | |
def run | |
@num += 1 | |
@@num += 1 | |
"the num is #{@num} and gloal counter is #{@@num}" | |
end | |
def self.sayHi | |
"Hi" | |
end | |
def Counter.sayHello | |
"Hello" | |
end | |
end | |
Counter::DESC | |
# ruby在任何地方能对一个既存的对象打开也是基于类的,只不过是个匿名的内部类而已, | |
# 而这个类继承于当前实例的类。 | |
a = Array.new | |
def a.hint | |
"array" | |
end | |
a.instance_eval do | |
def hint | |
"array" | |
end | |
end | |
class << a | |
def hint | |
"array" | |
end | |
end | |
# 类方法 | |
class Array | |
class << self | |
def hint | |
"array" | |
end | |
end | |
end | |
# 类方法 | |
class Array | |
def self.hint | |
"array" | |
end | |
end | |
# 类方法 | |
Array.instance_eval do | |
def hint | |
"array" | |
end | |
end | |
# 类方法 | |
class Array | |
def Array.hint | |
"array" | |
end | |
end | |
# 类实例方法 | |
class Array | |
def hint | |
"array" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# include & extend module | |
# include主要用来将一个模块插入(mix)到一个类或者其它模块。 | |
# extend 用来在一个对象(object,或者说是instance)中引入一个模块,这个类从而也具备了这个模块的方法。 | |
module Foo | |
def sayHi | |
"Hi" | |
end | |
end | |
class Array | |
def Array.sayHello | |
"Hello" | |
end | |
def sayHello | |
"Hello" | |
end | |
include Foo | |
extend Foo | |
end | |
a = Array.new | |
puts Array.sayHello | |
puts a.sayHello | |
puts Array.sayHi | |
puts a.sayHi | |
模块提供一个命名空间,实现方法mixin | |
require 加载模块 | |
其他和类几乎无异 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment