是否有可能在ruby中重新定義關鍵字and
?我有一些DSL這樣的代碼:Ruby在課堂上重新定義「和」關鍵字?
rule condition and another_condition do
do_something
end
我想and
僅僅是我的班內的另一個紅寶石方法就像condition
和another_condition
。這可能嗎?
是否有可能在ruby中重新定義關鍵字and
?我有一些DSL這樣的代碼:Ruby在課堂上重新定義「和」關鍵字?
rule condition and another_condition do
do_something
end
我想and
僅僅是我的班內的另一個紅寶石方法就像condition
和another_condition
。這可能嗎?
類似於and
和or
的關鍵字不能重載(重寫)。
本文介紹了運算符重載,並指定哪些運營商不能被重寫:
http://strugglingwithruby.blogspot.com/2010/04/operator-overloading.html
在文章的最後它指出:
You cannot override keywords, such as "or", nor can you override:
&& & || |() {} :: . ~ .. ...
更新
由於JörgW Mittag指出,那是錯誤的。 and
,or
,&&
和||
是唯一不能被覆蓋的運算符。 not
可以通過!
覆蓋。
它不受語言支持。
但是你可以隨時試用utils,如this之一。
恕我直言,重新定義Ruby關鍵字是一個非常糟糕的主意...... – spickermann
剛發現,這是不可能的。請參閱下面的答案。 – Stratus3D
要重新定義一個關鍵字,您必須更改底層C代碼並重新編譯,之後會因爲您引入的大量錯誤而崩潰。換句話說,忘記它。 –