Ruby创建“关键字”同名方法别名的方法
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方法类似。
相关推荐
PMJ0 2020-10-13
longzhiwen 2020-09-06
yangxingstar 2020-08-31
LUCIEN0 2020-08-17
huangzihao00 2020-08-17
Jan 2020-08-17
AndesStay 2020-06-12
afengxg 2020-06-09
zamesking 2020-06-09
afengxg 2020-06-09
何志文 2020-06-09
teresalxm 2020-06-05
何志文 2020-05-16
何志文 2020-05-11
fsl 2020-05-04
JOO 2020-04-26
倩 2020-04-22
afanti 2020-04-19
始终不够 2020-04-10