Created
September 8, 2015 02:57
-
-
Save lazybios/6a0ba09d44c1aa7ec440 to your computer and use it in GitHub Desktop.
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采用模块Mixin。模块是函数和常量的集合,若在类中包含一个模块,那么该模块的行为和常量也会成为类的一部分。 | |
# 定义模块ToFile | |
module ToFile | |
# 获取文件名 | |
def filename | |
"object_name.txt" | |
end | |
# 创建文件 | |
def to_f | |
File.open(filename, 'w') {|f| f.write(to_s)} # 注意这里to_s在其他地方定义! | |
end | |
end | |
# 定义用户类 | |
class Person | |
include ToFile | |
attr_accessor :name | |
def initialize(name) | |
@name = name | |
end | |
def to_s | |
name | |
end | |
end | |
Person.new('matz').to_f # 创建了一个文件object_name.txt,里面包含内容matz | |
==Begin | |
上面的代码很好理解,只是有一点要注意:to_s在模块中使用,在类中实现,但定义模块的时候,实现它的类甚至还没有定义。这正是鸭子类型的精髓所在。写入文件的能力,和Person这个类没有一点关系(一个类就应该做属于它自己的事情),但实际开发又需要把Person类写入文件这种额外功能,这时候mixin就可以轻松胜任这种要求。 | |
Ruby有两个重要的mixin:枚举(enumerable)和比较(comparable)。若想让类可枚举,必须实现each方法;若想让类可比较,必须实现<=>(太空船)操作符(比较a,b两操作数,返回1、0或-1)。Ruby的字符串可以这样比较:'begin' <=> 'end => -1。数组有很多好用的方法: | |
==End | |
a = [5, 3, 4, 1] | |
a.sort => [1, 3, 4, 5] # 整数已通过Fixnum类实现太空船操作符,因此可比较可排序 | |
a.any? {|i| i > 4} => true | |
a.all? {|i| i > 0} => true | |
a.collect {|i| i * 2} => [10, 6, 8, 2] | |
a.select {|i| i % 2 == 0} => [4] | |
a.member?(2) => false | |
a.inject {|product, i| product * i} => 60 # 第一个参数是代码块上一次执行的结果,若不设初始值,则使用列表第一个值作为初始值 | |
#http://raytaylorlin.com/Tech/Script/ruby-language-2/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment