10 Ruby Tricks You Haven’t Learned Yet

In this lesson we will learn about 10 ruby tricks which you have never heard of. These tricks will make you a better Ruby programmer.

10 Ruby Tricks You Haven’t Learned Yet

1. Deep copy

When you copy an object that contains other objects, like an Array, only a reference to these objects is copied.

You can see that in action here:

Using the Marshal class, which is normally used for serialization, you can create a ‘deep copy’ of an object.

The results:

2. Different ways to call a lambda

If possible, you should stick with the first one (call), because it’s the one most people know.

3. Creating a pre-filled array

The Array class can take an argument + a block, which lets you create an array with n elements. By default these elements are nil, but if you have a block, the values will come from it.


This will generate an array with 10 random numbers which are between 0 and 299.

4. True, false and nil are objects

There is only one copy of these objects, and you can’t create more even if you wanted.

5. Lambdas are strict about arguments, but Procs don’t care

6. Execute code directly without irb or files

The ruby command has a number of interesting options you can use.

For example, with the -e flag you can pass in a snippet of code to be executed.

You can find more by using the -h flag.

7. Your own mini-irb in one command

Ever wanted to know how irb works? Well, this is a super-simple version of it.

Remember what ‘REPL’ stands for: Read-Eval-Print Loop.

You won’t get a prompt, but go ahead and type some Ruby code.

This works because the -n flag does this:

And $_ is a global variable. Which contains the following:

8. Unfreeze an object (danger!)

There isn’t any Ruby method to unfreeze an object, but using the Fiddle class you can reach into Ruby internals to make it happen.

Don’t try this at home!

9. Objects with special identity

Ruby objects have an identifier or ‘id’ number you can access using the object_id method. Some objects have a fixed id: Fixnums, true, false & nil.

Fixnum ids use this formula: (number * 2) + 1.

Bonus: The maximum Fixnum is 1073741823, after that you get a Bignum object.

10. Avoid big output in irb or pry

If you are working in irb and want to avoid filling your screen with the contents of some really big array or string you can just append ; at the end of your code.


Try again without the ; to see the difference