Ruby Tips & Tricks

Discussion in 'Ruby on Rails' started by pradeep, Aug 9, 2013.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    In this article I would to share a few lesser known coding tips & tricks in Ruby language, this has helped me make my code shorter and write code quicker, nevertheless the more you know the higher the chances of finding out some trick yourself.

    Delete a directory tree



    Sometimes, we need to delete whole directories, and I have seen people resorting to the use of shell command for the purpose, but that is not needed. Ruby has a module fileutils which is better.

    Code:
    require 'fileutils'
    FileUtils.rm_r '/tmp/myTempDirectory/'
    

    Using Non-Strings or Symbols as Hash key



    This nice trick is very handy, checkout the example below:

    Code:
    is = { true => 'Yes', false => 'No' }
    
    p is[ 10 == 11 ] # -> No
    p is[ 10 > 9 ] # -> Yes
    

    Easy way to join array elements



    Did you know that you can join arrays using the * operator? Here's how:

    Code:
    p [1,2,3,4] * " | " # -> "1,2,3,4"
    p %w{pradeep anjali asha} * "," # -> "pradeep,anjali,asha"
    
    Applying the * operator to an array with a number will increase the size of the array, but passing a string will join the array using the passed string as delimiter.

    Use ranges for comparison of numbers



    Now you would need to combine multiple conditions with and/or, just use this:

    Code:
    number = 4
    
    suffix = case number
               when 1 then "st"
               when 2 then "nd"
               when 3 then "rd"
               when 4..10 then "th"
         end
    
    puts number.to_s << suffix
    

    Interpolating Strings easily



    Interpolate format strings and substitute with values easily like this:

    Code:
    vars = %w{Anjali 3 Kolkata}
    
    puts "%s is %s and stays in %s" % vars
    
     
    shabbir and coderzone like this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice