Posts

Showing posts from June, 2015

Asterix with arguments in Ruby

Lets create a method that accepts number of arguments
def my_method(x, *y, **z) return x, y, z end Concept : x is a regular parameter. *y will take all the parameters passed after the first one and put them in an array. **z will take any parameter given in the format key: value at the end of the method call

See the following examples:

One parameter
my_method(1) # => [1, [], {}] More than one parameter
my_method(1, 2, 3, 4) # => [1, [2, 3, 4], {}] More than one parameter + hash-style parameters
my_method(1, 2, 3, 4, a: 1, b: 2) # => [1, [2, 3, 4], {:a=>1, :b=>2}]

Date Localization and formatting

I18n.l is the easiest way to do it

I18n.l(@user.created_at)
And in case you want to use a different format :

I18n.l(@user.created_at, :format => :short)
You will find more documentation here