Share this!

11 Ruby Tricks You Haven’t Seen Before

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.

Example:

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.

This is the singleton pattern in action.

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.

Example:

Try again without the ; to see the difference :)

11. Using the caller method to get the current call stack

Here is a code example:

Output:

If you need the current method name you can use __method__ or __callee__.

Bonus! Convert any value into a boolean

That’s all!

I hope you enjoyed these ruby tricks! Please share them with you friends and subscribe to my blog in the form below :)

20 comments
Alex says January 19, 2016

Thanks, Jesus!
I like your blog :)
Just want to add a little detail to trick 10: I think that just putting ‘;’ after any ruby code will suppress the output.
RestClient.get('blackbytes.info');

    Jesus Castello says January 19, 2016

    You are right! Thanks for pointing that out :)

    flimflan says January 21, 2016

    But in (my) irb, just leaving a trailing ; will not execute the expression. It is now waiting for another expression on a new line. I usually append ‘;nil’.
    Maybe there is another dependency (readline?) in play.

Serguei Cambour says January 19, 2016

Thank you so much, Jesus, it’s really kind of you to share such useful tricks! Cheers

    Jesus Castello says January 19, 2016

    Thank you. I’m glad you found them useful :)

ttw (@ttwo32) says January 19, 2016

Good article.There are some tricks i have not seen before.

    Jesus Castello says January 19, 2016

    Thanks for reading :)

Sufinsha says January 20, 2016

Good Tricks

Nirmal says January 20, 2016

Good one, thanks for posting :)

    Jesus Castello says January 20, 2016

    Thanks for reading!

Arthur Shagall says January 21, 2016

My inner troll politely asks, “What happens when you deep clone objects which are actually just wrappers over external resources, i.e. sockets, file handles, db connections, etc.?”

    Jesus Castello says January 21, 2016

    That’s an interesting question :)

    I just ran a quick test and the answer is simple: Ruby won’t let you do it.

    I tried with a socket and I get: TypeError: can't dump TCPSocket.

William Hatt says January 21, 2016

Adding “;” to the end of the line will also let you create a function on a single line. IE: def hello_world; puts “Hi”; end

Vinoth says January 21, 2016

For #1, for a simple string array, we could also use the following.

food.map(&:clone).map(&:object_id)

May be, if the objects are deep by multiple levels, marshaling could be a way.

Michael says January 21, 2016

Calling a lambda with triple equal doesn’t make a whole lot of sense to me :)

    Jesus Castello says January 21, 2016

    This is a thing because case statements use ===.
    You can read more about that in this post.

MadBomber says January 21, 2016

Trick #3 incorrectly states “This will generate an array with 10 random numbers which are between 0 and 300.”

Actually rand(max) generates a number less than max: 0 <= n < max

http://ruby-doc.org/core-2.3.0_preview1/Random.html#method-i-rand

    Jesus Castello says January 21, 2016

    You’re right. I have corrected the problem, thanks for letting us know.

Steve Shreeve says January 22, 2016

Here’s another one for your list… a little gem which uses Fiddle to access an otherwise internal-only part of Ruby itself to access the bindings of any caller of a function. If a calls b, which calls c, which calls d… then the ‘bindings’ gem will allow the d method to access variables defined in c, b, or a. The code is tiny and has been extremely helpful for us!

Check it out at: https://github.com/shreeve/bindings

    Jesus Castello says January 22, 2016

    Thank you :)

Comments are closed