Ruby Tricks

I guess this is my first post.

Two awesome Ruby features I've learned.

 

Monkey Patching

Matt showed me this a few months back. For this example, 'monkey patching' is dynamically rewriting a class.

In Ruby, numbers use the class Fixnum. 1 is a Fixnum, 2 is a Fixnum, etc.
We're going to overwrite (override?) the Fixnum class. You don't need to rewrite every single method, just the ones you want to change. How about overwriting the + method?

When you type 4+4 in Ruby, it gets interpreted as 4+(4); + is really a method of the object 4. You can see this for yourself with 4.methods. Somewhere close to the beginning, you'll see "to_sym", "*", "ord", "+", and so on.
+ is in there!

class Fixnum  
    def +(num_to_add)
        self-num_to_add
    end
end  

Try doing some simple addition after that. The second number is subtracted, not added!
If you did this in irb, then the change only lasts for that session. If it's in a file, then the change is only active while the file is running. Essentially, ruby will not reverse addition for all of eternity unless you keep it running that long.
 

Spaces in method and variable names?!

I read about this here.

Ever seen that special HTML space character,  ? Stands for non-breaking space. Here's what you can do with that.

Open up a new text (ruby) file, and type in

apple count=1  
puts apple count  

Before you save and run it, make sure you save it with UTF-8 encoding.

You should get a NameError about undefined local... apple. This is because Ruby interprets this code as you trying to call the method apple, with argument count. As in, puts apple(count)

Now, go copy this non-breaking space character | | or you can just use option+space on Mac. Replace the space between both apple counts with the non-breaking space.

Running the program again should print 1!
As shown in the post I linked to, you can also name variables and methods with nothing but non-breaking spaces. Again, as the post says, please don't use that in production code!!
You can also put other various utf-8 characters in ruby programs:

suits=["♠","♣","♥","♦"]  
10.times do  
    puts "#{rand(13)+1} of #{suits.sample}"
end  

Hope you enjoyed reading about these two cool Ruby features!