Sunday, October 12, 2008

(5)Ruby中的关键字

下列关键字在Ruby中有特殊的含义:

__LINE__      case         ensure       not          then
__ENCODING__ class false or true
__FILE__ def for redo undef
BEGIN defined? if rescue unless
END do in retry until
alias else module return when
and elsif next self while
begin end nil super yield
break
除此之外,以下三个关键字如果出现在代码行的开头,那么他们有特殊的含义:
=begin =end __END__
就像我们前面介绍的那样,=begin和=end 用于多行注释,__END__代表一段程序的结束,他的前后都不能有其他字符。
以上提到的关键字在其它语言里通常被称为“保留字”,也就是说你不可以把它们当作变量、类名等使用,但是在Ruby中如果你以$,@,@@开头来使用这些关键字是没有问题,它们仍然被当作你自己的标识符,但是我们建议最好不要这样做,这样容易引起歧义,不利于代码阅读。
很多Ruby的重要特性都实现为了相应的方法,所以我们最好把下面的关键字也作为保留字对待:

# 这些为出现在语句中的关键字
at_exit catch private require
attr include proc throw
attr_accessor lambda protected
attr_reader load public
attr_writer loop raise

# 这些为通常的全局函数
Array chomp! gsub! select
Float chop iterator? sleep
Integer chop! load split
String eval open sprintf
URI exec p srand
abort exit print sub
autoload exit! printf sub!
autoload? fail putc syscall
binding fork puts system
block_given? format rand test
callcc getc readline trap
caller gets readlines warn
chomp gsub scan

# 这些为通常用于对象的方法
allocate freeze kind_of? superclass
clone frozen? method taint
display hash methods tainted?
dup id new to_a
enum_for inherited nil? to_enum
eql? inspect object_id to_s
equal? instance_of? respond_to? untaint
extend is_a? send

No comments: