Can we overide true and false methods in Ruby?

Viewed 239

Is it possibile to override boolean method like true and false in Ruby?

For example

def true
   rand()
end

def false
   rand()
end

true  #=> 0.7548583661438558
false #=> 0.19239076750079454

If I try the above, I get:

true  #=> true
false #=> false

I'm trying to understand where these true, false methods are defined.

I know that && and || can't be overriden, because && and || are short circut operators.

Are true and false similar? or they are written inside Ruby somewhere?

I'm just experimenting with Ruby.

1 Answers

true and false cannot be overridden because they are keywords, not methods. Their values are hard-coded and there's no way to re-assign a different value. (at least not from within Ruby)

Even when implementing a method with the same name, a literal true will still resolve to the built-in value.


What you can do is change the object, true is resolving to for interesting results: (this is just for fun, don't do this in actual code)

def true.inspect
  rand.to_s
end

true #=> 0.8499100640573652
true #=> 0.22279583303254913

However, the above example doesn't actually change the value of true in any way. Also, don't think of true as a method invocation returning a random float every time it is called. We are looking at the very same object:

a = true

a #=> 0.5813338288658235
a #=> 0.6447125630746154

What we did is change its representation by overriding inspect, which:

Returns a string containing a human-readable representation of obj.

We see those floats because IRB calls inspect in an attempt to print the last expression's result in a readable way.

If we set IRB's output mode to :to_s, our change is bypassed and we see true again:

IRB.CurrentContext.inspect_mode = :to_s

a    #=> true
true #=> true
Related