Книга: Metaprogramming Ruby 2
Назад: Method Wrappers
Дальше: Wrap-Up

Quiz: Broken Math

Where you find that one plus one doesn’t always equal two.

Most Ruby operators are actually methods. For example, the + operator on integers is syntactic sugar for a method named Fixnum#+. When you write 1 + 1, the parser internally converts it to 1.+(1).

The cool thing about methods is that you can redefine them. So, here’s your challenge: break the rules of math by redefining Fixnum#+ so that it always returns the correct result plus one. For example:

 
1 + 1 ​# => 3

Quiz Solution

You can solve this quiz with an Open Class (). Just reopen Fixnum and redefine + so that (x + y) becomes (x + y + 1). This is not as easy as it seems, however. The new version of + relies on the old version of +, so you need to wrap your old version with the new version. You can do that with an Around Alias ():

 
class​ Fixnum
 
alias_method :old_plus, :+
 
 
def​ +(value)
 
self.old_plus(value).old_plus(1)
 
end
 
end

Now you have the power to wreak havoc on Ruby’s basic arithmetic. Enjoy this code responsibly.

Назад: Method Wrappers
Дальше: Wrap-Up