Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Aug 31 ’11

Convert Object to Array

Have you ever been in a situation where you needed a method that does all of the following?

  • Convert nil to an empty Array, and
  • convert a non-Array variable n to [n], and
  • leave the Array variable as is.

The way to achieve this, is using the little known method Array():

Array(nil) # => []
Array([])  # => []
Array(1)   # => [1]
Array([2]) # => [2]

(Source: rubyloveinfo)

5 notes 0 comments (via rubyloveinfo)

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus