4 ms·
So, "nil" is not a primitive value in Ruby explains the extra care taken with these control flow statements in the language. Let's get back to the example, let
by gotchange 11y ago
So, "nil" is not a primitive value in Ruby explains the extra care taken with these control flow statements in the language.
Let's get back to the example, let's say that checking for «u» would return «nil», wouldn't checking for «u.profiles» would result in an exception thrown nonetheless?
- spoiler 11y ago> So, "nil" is not a primitive value in Ruby Almost nothing is a primitive value in Ruby. Not even true/false/numbers are "traditional" primitive values. > Let's get back to the example, let's say that checking for «u» would return «nil», wouldn't checking for «u.profiles» would result in an exception thrown nonetheless? No, because `u.?profile` would return `nil`, then, when you try `nil.?thumbnail` on nil again, it would return nil. So, doing the following, with `u` being `nil` is legal: if u.?profile.?thumbnail # doesn't run if u is nil end
- vidarh 11y agoEverything 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).