Wednesday, September 29, 2010

Using nil.to_a or whatever.to_a in ruby

Ruby is a programming language for developer happiness and productivity for customers. Here is a quick happiness and productivity tip:

#You have seen something like this, if null replace with a blank array
an_array = (another_array || [] ) + (yet_another_array || [])
#But you could do this as well
an_array = another_array.to_a + yet_another_array.to_a
#Or you have seen this
an_array = another_array + (an_element_or_array.is_a?(Array) ? an_element_or_array : [an_element] )
#But you could do this
an_array = another_array + an_element_or_array.to_a
Happy? I am happy!
view raw nil.to_a.rb hosted with ❤ by GitHub