Ruby Verbose Warning Mode

Ruby在很多方面是一个更优雅的Perl,从Perl社区继承了很多文化。其中之一就是:以verbose warning模式运行Ruby。

Ruby是一个非常宽松的语言,她运行你访问一个未定义的实例变量,允许你动态对原有的类的方法进行增删改查操作,甚至允许你给一个常量重新赋值…

但这仅仅是允许,并不代表Ruby支持你这样做。

以warning模式运行你的程序,这样就可以为你发现一些不小心而犯的错误,比如拼写错误和无意的覆盖了别人的方法。

不幸的是,默认情况warning模式是关闭的,你可以在运行Ruby时加上-w参数来开启。

如果你你的代码有一些洁癖,每次运行程序开启warning模式,解决掉输出警告的代码行是一件很有趣的事情。

下面看看一个例子:

@use_less_variable

def redefinition_method;end
def redefinition_method;end

REDEF_CONST = 23
REDEF_CONST = 42

def mismatched_indentation
end

def undefined_instance_variable
@instance
end
undefined_instance_variable

names = %w{hooopo rubyist}
names.map{|names| names + " hello"}

puts(1 +2)


两次运行结果如下:

[quote]hooopo@hooopo:~$ ruby warning.rb
warning.rb:7: warning: already initialized constant REDEF_CONST
3
[/quote]

[quote]
hooopo@hooopo:~$ ruby -w warning.rb
warning.rb:10: warning: mismatched indentations at ‘end’ with ‘def’ at 9
warning.rb:18: warning: shadowing outer local variable – names
warning.rb:20: warning: `+’ after local variable is interpreted as binary operator
warning.rb:20: warning: even though it seems like unary operator
warning.rb:1: warning: useless use of a variable in void context
warning.rb:4: warning: method redefined; discarding old redefinition_method
warning.rb:3: warning: previous definition of redefinition_method was here
warning.rb:7: warning: already initialized constant REDEF_CONST
warning.rb:13: warning: instance variable @instance not initialized
3[/quote]
第一次运行没有加warning模式,只报了一个常量已经初始化警告,第二次以warning模式运行,所有的警告都打印出来了。

[quote]mismatched indentations at ‘end’ with ‘def’ at 9[/quote]

这是一个缩进没有对齐的警告

[quote]shadowing outer local variable – names[/quote]

这个一般发生在具有闭包语法的语言中,当两个不同的局部变量具有相同的名字时,内部作用域的变量会遮住外部作用域的变量。

[quote]`+’ after local variable is interpreted as binary operator even though it seems like unary operator[/quote]

这句是说+号被解析成了二元操作符,即使它看起来像一元操作符。

[quote]useless use of a variable in void context[/quote]

没有用到的变量

[quote]method redefined; discarding old redefinition_method 和 previous definition of redefinition_method was here[/quote]

当方法被覆盖之后会有警告,并且会提示你被覆盖的方法原来定义在什么位置

[quote]instance variable @instance not initialized[/quote]

实例变量没有初始化就使用了

总之,Ruby的openclass和元编程特性给了程序员更大的自由。但是我们自己应该清楚自己的每行代码到底做了什么。 这样才能充分发挥自由带来的便利,而不是混乱。经常在warning模式下运行你的代码,清理恼人的warning是让你的代码长期稳定运行的保证。

[url=http://rubyeye.herokuapp.com/articles/15-ruby-verbose-warning-mode-1]Ruby Verbose Warning Mode (1)[/url]
[url=http://rubyeye.herokuapp.com/articles/16-ruby-verbose-warning-mode-2]Ruby Verbose Warning Mode (2)[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值