首页 > 学院 > 开发设计 > 正文

Ruby 魔法 学习笔记之一

2019-10-26 19:22:15
字体:
来源:转载
供稿:网友
一、向对象显示的发送消息
我们可以向对象直接发送消息:
Ruby代码
代码如下:
class HelloWorld
def say(name)
print "Hello, ", name
end
end
hw = HelloWorld.new
hw.send(:say,"world")

我们通常使用hw.say("world"),但send可以对private的方法起作用。
不光如此send可以使程序更加动态,下面我们看看一个例子:
我们定义了一个类Person,我们希望一个包含Person对象的数组能够按
照Person的任意成员数据来排序:
Ruby代码
代码如下:
class Person
attr_reader :name,:age,:height
def initialize(name,age,height)
@name,@age,@height = name,age,height
end
def inspect
"#@name #@age #@height"
end
end
在ruby中任何一个类都可以随时打开的,这样可以写出像2.days_ago这样优美
的code,我们打开Array,并定义一个sort_by方法:
Ruby代码
class Array
def sort_by(sysm)
self.sort{|x,y| x.send(sym) <=> y.send(sym)}
end
end
我们看看运行结果:
Ruby代码
people = []
people << Person.new("Hansel",35,69)
people << Person.new("Gretel",32,64)
people << Person.new("Ted",36,68)
people << Person.new("Alice", 33, 63)
p1 = people.sort_by(:name)
p2 = people.sort_by(:age)
p3 = people.sort_by(:height)
p p1 # [Alice 33 63, Gretel 32 64, Hansel 35 69, Ted 36 68]
p p2 # [Gretel 32 64, Alice 33 63, Hansel 35 69, Ted 36 68]
p p3 # [Alice 33 63, Gretel 32 64, Ted 36 68, Hansel 35 69]
这个结果是如何得到的呢?
其实除了send外还有一个地方应该注意attr_reader,attr_reader相当于定义了name,
age,heigh三个方法,而Array里的sort方法只需要提供一个比较方法:
x.send(sym) <=> y.send(sym) 通过send得到person的属性值,然后在使用<=>比较
二、定制一个object
<< object
ruby不仅可以打开一个类,而且可以打开一个对象,给这个对象添加或定制功能,而不影响
其他对象:
Ruby代码
a = "hello"
b = "goodbye"
def b.upcase
gsub(/(.)(.)/)($1.upcase + $2)
end
puts a.upcase #HELLO
puts b.upcase #GoOdBye
我们发现b.upcase方法被定制成我们自己的了
如果想给一个对象添加或定制多个功能,我们不想多个def b.method1 def b.method2这么做
我们可以有更模块化的方式:
Ruby代码
b = "goodbye"
class << b
def upcase # create single method
gsub(/(.)(.)/) { $1.upcase + $2 }
end
def upcase!
gsub!(/(.)(.)/) { $1.upcase + $2 }
end
end
puts b.upcase # GoOdBye
puts b # goodbye
b.upcase!
puts b # GoOdBye
这个class被叫做singleton class,因为这个class是针对b这个对象的。
和设计模式singleton object类似,只会发生一次的东东我们叫singleton.
<< self 给你定义的class添加行为
Ruby代码
class TheClass
class << self
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表