Everything is an Object.
Ruby 彻底贯彻了 Everything is an object 这个最基础的 OOP 思想,甚至连数,布尔值与空值 nil (as null in Java) 和类 (class) 本身都属于对象。
1 | > -42.abs |
数 -42 是 Fixnum 类的对象。在该类中定义了方法 abs,因此 -42 可以直接调用该方法。所有的对象都定义了 nil? 方法;对于 nil 类的对象,该方法返回 true;反之返回 false。
注意到以上的代码都是在 REPL 中进行的:这是因为 Ruby 提供了很多方法支持 reflection。举例来说,methods 方法返回一个 list,其中存储某个对象所定义的全部方法;而 class 方法则返回某个对象的类。这些方法均可以在程序运行时进行调用。
reflection. Learning about objects and their definition during program execution.
Such reflection is occasionally useful in writing flexible code; it is also useful in the REPL or for debugging. Refer to this article for detailed explanation.