Word Array
Here’s a very handy way to create arrays that not everyone knows:
%w(vi du 1})=> # "vi, du, 1"
Chain concatenation
For repeated strings we can use the * operator:
[1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3] # true
Decimal Number Format
When you want to display decimals in a certain format:
1 2 3 | number = 9.5 "%.2f" % number # => "9.50" |
Delete Folder
This is a relatively common job that programmers face. There are many different ways to delete directories and this is one of the shortest and fastest ways to do the above:
1 2 3 | require 'fileutils' FileUtils.rm_r 'somedir' |
Note: Check carefully the files in the directory before running the above command because after deleting these files can not be restored.
Massive Assignment
Massive assignment in Ruby allows you to assign values to multiple variables at the same time:
a, b, c, d = 1, 2, 3, 4
This feature is particularly useful for methods with multiple parameters:
1 2 3 4 | def my_method(*args) a, b, c, d = args end |