begin和end是ruby的关键字,但是Range中也有名称为begin和end的实例方法。现在问题来了:怎么创建它们的别名方法?
如果用class Range;alias begin_x begin end是不行的,ruby以为后面一个begin是某个语法块的开头啊:
2.1.2 :089 > class Range;alias begin0 begin end
2.1.2 :090?>
用class Range;alias begin_x "begin" end也不行,用alias begin_x :begin还是不行!
2.1.2 :083 > class Range
2.1.2 :084?> alias begin0 :begin
2.1.2 :085 > end
2.1.2 :086?> end
SyntaxError: (irb):86: syntax error, unexpected keyword_end, expecting end-of-input
from /Users/apple/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'
2.1.2 :087 > class Range;alias begin0 "begin" end
SyntaxError: (irb):87: syntax error, unexpected tSTRING_BEG
class Range;alias begin0 "begin" end
^
from /Users/apple/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'
没法子了吗?我突然想到了这个语法:alias begin_x :"begin",这回哦鸟!同样的end方法类似。