变量一定要有类型吗(一)

先讨论一下Ruby是不是强类型。


1).在《Beyond Java》[size=7]September 2005[/size] 一书 6.1.2节Typing 中,Bruce Tate举例
irb(main):015:0> "fish"+4
TypeError: cannot convert Fixnum into String
from (irb):15:in‘+’
from (irb):15
从而得出结论:
[quote] That means Ruby is strongly typed.[/quote]

我们知道,Ruby是动态语言,在运行中边解释、边检测、边执行,检测类型匹配吗?不是检测类型匹配,而是检测语法。
String类的‘+’是一个方法,但是,Ruby从来不拒绝你重写方法。

class String
alias : old_plus :+
def +(other)
self.old_plus(other.to_s)
end
end

puts "fish"+4 # => fish4
puts '1 ' + 2.3 # => 1 2.3



2).Bruce Tate 在“跨越边界: Java 模型以外的类型策略”[size=7]2006 年 6 月[/size] 一文中写到:
[quote]...这两种语言都 [u]倾向于[/u] 强类型...[/quote]

这两种语言是指Java和 Ruby,他给出了一行Ruby代码来说明;

1 + "hello"
会收到以下错误消息:
TypeError: String can't be coerced into Fixnum
from (irb):3:in '+'
from (irb):3


字面值1是Fixnum类的实例对象,让我们重写Fixnum类的‘+’方法,使得‘+’的语法不再出错;


class Fixnum
alias : old_plus :+
def +(other)
(other.class.eql?String) ? (self.to_s << other) : (old_plus(other))
end
end

puts 1 + "hello" # => 1hello
puts 1 + " 2.3" # => 1 2.3



3). Ruby是简单的,我们可以只管按照别人说的去使用;Ruby也是灵活而复杂的,我们可以按照自己的需求去使用;

require "another_plus3"

puts 'he'+1 # => he1
puts '1.5'+2 # => 3.5
puts 1+" he" # => 1 he

puts 1 + " 2.3" # => 3.3
puts 1 + 2.3 # => 3.3

puts 1.6 * "2.7" # => 4.32
puts 1 -"2.3" # => -1.3

类型错误根本不存在,如果语法错误算是强类型,我无言。Bruce Tate是大牛,他断言Ruby是强类型,国内的牛们也跟着如是说。
在1).中, Bruce Tate断言Ruby是强类型;
在2).中, Bruce Tate认为Ruby 倾向于 强类型。

后文“变量一定要有类型吗(二)”将更进一步说明。



#another_plus3.rb

class String

alias : old_plus :+
def +(other)
(Float(self)) + (Float(other)) rescue (self.to_s).old_plus(other.to_s)
end

def coerce(other)
case other
when Integer : return other, Integer(self) rescue return Float(other), Float(self)
when Float : return other, Float(self)
else super
end
end

end

class Fixnum
alias : old_plus :+
def +(other)
(other.class.eql?String)?(old_plus(Float(other)) rescue self.to_s<<other):(old_plus(other))
end
end

class Float
alias : old_plus :+
def +(other)
(other.class.eql?String)?(old_plus(Float(other)) rescue self.to_s<<other):(old_plus(other))
end
end


========
题外话

假设若干年后,有一篇搜索引擎报告指出:
A)21世纪初期,网络信息以中文和英文居多;
B)其中中文信息多数是英文信息的跟风之作,
从发布时间得出,英文信息居前;
从信息不确切度得出,中文信息没有经过中文世界的思维、理解与吸收,英文信息如何错误,中文信息也有相似度极高的错误...
...

我衷心地希望与你,一起唱和出中文技术论坛自身的弦音。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值