Ruby tips

I just read the Ruby Pocket Reference, a great intro for the Ruby language and want to share a few helpful Ruby tips learned.

Parallel assignment of variables

In Ruby, you can assign several values to several variables in a single expression (aka. one-liner). The values can be of any type, making it even better! The result is pretty impressive, check out the snippet below :

You can even return multiple values from methods!

And in case the above example didn’t quite impress you, see how convenient it can be on a real-world example :

Here Documents

You can build multiple line strings using here documents. Ruby supports both single and double-quoted strings on here documents, have a look at the examples :

Ranges

Ruby supports ranges of numbers which can be very handy. You can define a range of numbers using the starting value followed by .. (2 dots) or ... (3 dots) and the end value. On the first case the range includes the last value, and on the other one excludes it. For example :

Ranges can be used in many cases such as :

Loops

Comparison

and creating arrays

Default arguments

Another great feature!

block_given? on yields

A yield statement executes a code block associated with a method. You probably know that already (if not have a look at the examples below), what you probably don’t know is the block_given? method that checks if a code block is passed to the method.

Case statement tricks

Case staments in Ruby are very flexible. They come in two main flavors, multiline for writing many statements and one-liners, that looks much better:

You can also assign a value using the case statement in Ruby:

Usefull object instance methods

As a final tip, I enlist the most useful public methods of the Object class (the base class for Ruby, all other types inherit these methods). All of them are helpful, but I tend to use the debugging-oriented ones the most :

  • obj.inspect
  • obj.class
  • obj.ancestors
  • obj.instance_variables
  • obj.methods (also obj.private_methods, obj.protected_methods and obj.public_methods can be handy as well)
  • obj.to_s (sometimes obj.to_a can be handy as well)

Not bad for an introductory Ruby book. If you like the post stay tuned for more!

Leave a Reply