3 ms·
Everything is an object in Ruby. E.g. you can do "42.to_s(16)" to convert 42 to base 16. That includes nil, true, false (instances of NilClass, TrueClass and F
by vidarh 11y ago
Everything is an object in Ruby. E.g. you can do "42.to_s(16)" to convert 42 to base 16.
That includes nil, true, false (instances of NilClass, TrueClass and FalseClass respectively).
A common way of explicitly checking for nil, as opposed to nil or false is to do "foo.nil?", for example, which explicitly calls the method nil? on foo, which will usually return false for objects other than nil (nothing stops you from overriding it if you want your class to pretend to be nil - e.g. maybe I'd want my "Maybe" class to return true for "nil?" if the value it holds is nil).
As for the example the whole point is that like my naive "Maybe" implementation, this new operator would check if the target is nil before trying to call a method. Unlike my naive implementation, it doesn't need to wrap objects, and it can short-circuit evaluation if it meets a nil (you can implement versions that will short-circuit evaluation too, but I can't see any obvious ways of both letting you short-circuit and getting "clean" syntax if you want to support method arguments).