/ beginner

3 min reading - must know hacks for ruby beginners

Here are 5 ruby hacks and 5 practices/concepts you need to know when you start ruby language.

go play around with this (awesome) online ruby console to check all it out

1 - Operators

ruby has a lot of operators but &., &&= and ||= are awesome:

if my_object && my_object.my_property && my_object.my_hash.my_property
    # long
end

if my_object&.my_hash&.my_key
    # short
end

my_var = my_method()

# long
my_var = my_var && my_var.first
my_var = my_var || ['long']

# short
my_var &&= my_var.first
my_var ||= ['short']

2 - Map method

ruby has a super cool system of map/yield/lambda/block stuff
but here is one hack called Symbol#to_proc:

# long
pps = my_collection.map {|elem| elem.pp }

# short
pps = my_collection.map(&:pp)

3 - Error handling

As most of regular languages ruby have a system of error handling, but there is the long and the short way:

#long
def my_method
    # blabla
    begin
        # blabla
    rescue => e
        # oops
    ensure
        # potatoes
    end
end

# short
def my_method
    # blabla
    # blabla
rescue => e
    # oops
ensure
    # potatoes
end

4 - Arrays ❤️ ranges

Ruby ranges is an awesome thing combined with arrays:

# declare an already fullfield array with whatever sequence
num_array  = [*1..5]     # => [1, 2, 3, 4, 5]
alph_array = [*'a'..'e'] # =>  ['a', 'b', 'c', 'd', 'e']

# slice it (negative index -x means position x from the end)
num_array [2..4]         # => [2, 3, 4]
alph_array[2...4]        # => ['b', 'c']
num_array [3..-1]        # => [3, 4, 5]
alph_array[-4..-1]       # => ['b', 'c', 'd', 'e']

5 - Bang methods

Ruby uses bang methods (ended with !) for methods that (most of the time) modify the object they are call on :

# long
my_collection = my_collection.map(&:pp)
my_string     = my_string.upcase

# short
my_collection.map!(&:pp)
my_string.upcase!

Here are now some things you might see that can look strange when you are a ruby noob and you read some ruby ninja code :

1 - Return

In ruby, if no return keyword is provided, the method will return the last evaluated value (but you must use it for multiple values):

def meth1
    return 'OK'
end

def meth2
    'OK too'
end

def meth3(my_bool)
    if my_bool
        'OK'
    else
        'OK too'
    end 
end

meth3(false) # => 'OK too'

most of the time, when you can avoid it, do so

2 - Method calling

As you may notice, you can make abstraction of () when you are calling a methods without params. Good news, you can omit them too even with params (even it's less readable) :

# OK
my_obj.get_pp(true).upcase.split('|', 4) 

# OK too
my_obj.get_pp(true).upcase.split '|', 4

# NOT OK
my_obj.get_pp true .upcase.split '|', 4

3 - To self or not to self

In your ruby class/object, you can sometimes make abstraction of self (which is a keyword to access the current object/instance itself), and sometimes you cannot ¯\(ツ)

class MyClass
    # CLASS methods
    self.class_method
        'this works well'
    end

    self.class_method_2
        # both OK
        class_method
        self.class_method
    end
    
    # INSTANCE methods
    def instance_method
        'I love golang'
    end
    
    def my_attr=(string)
        @my_attr = string.downcase
    end
    
    def meth4
        # all OK
        puts instance_method
        puts self.instance_method
        puts MyClass.class_method
        
        # NOT OK
        puts class_method
        
        # OK
        self.my_attr = "New_ValUe"

        # NOT OK, this will just create a new variable 'my_attr'
        # instead of calling 'my_attr=' method
        my_attr = "nEW_vALuE"
        
    end
end

most of the time, when you can avoid it, do so

4 - 0 is not falsy

It may be obvious (or not) for you according to your background but once for all :

puts false ? 'true' : 'false'
# => 'false'
puts nil   ? 'true' : 'false'
# => 'false'

puts 0     ? 'true'  : 'false'
# => 'true'

4 bis - logical && and || operators returns values, not booleans

Again, depending on your background it can be logic (or not).

my_var = 1 || 2
puts my_var
# => 1
my_var = 1 && 2
puts my_var
# => 2

5 - Block / lambda / yield (again ?)

In fact there is nothing for me to share in particularly. Just be aware that you may be lost. In my darkest moments, I am still... There is nothing to do but to google it again and again until you got it.


To finish this, I highly recommend you to install and use ruby-robocop into whatever IDE you are using. This will help you to code with extreme good practices from the very beginning.

nathan gouy

nathan gouy

!! > Looking For a Job in Canada < !! Currently working at diduenjoy as a full stack Js/Ruby lead dev. Very curious and creative, I express it through development, cooking and DIY.

Read More
3 min reading - must know hacks for ruby beginners
Share this

Subscribe to Nathan gouy Blog