Wednesday, June 19, 2013

Prepending in a Ruby Array

Appending in Ruby array is done in the following way :

my_array = ['s','a','u','r','a'] => ["s", "a", "u", "r", "a"]
my_array << 'v' => ["s", "a", "u", "r", "a", "v"]

Now, if you want to prepend any value to an array, Ruby's unshift method can be used for this purpose.

my_array => ["s", "a", "u", "r", "a", "v"]
my_array.unshift('c') => ["c", "s", "a", "u", "r", "a", "v"]

Thats it !

Monday, June 10, 2013

Ruby's try()

I came to know about Ruby's try() method today, liked, the overall purpose of this method and so, sharing a brief note about how we can use this method while writing codes. 

Many a times, we have to write conditions for checking for nil values/objects. try() can help us to write clean codes whereby we don't have explicitly do testing for nil value. 

Have a look at the small example below 

Without try():
puts @student.school.name if @student.school
With try():

puts @student.school.try(:name)

Read this http://apidock.com/rails/Object/try link, to know about try() method more in details.