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]

5 notes 0 comments (via rubyloveinfo)

  1. nepalonrails-blog-blog liked this
  2. rubyquicktips reblogged this from rubyloveinfo
  3. thestralssecret liked this
  4. danielpietzsch liked this

Comments

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

View the discussion thread.
blog comments powered by Disqus
[フレーム]

AltStyle によって変換されたページ (->オリジナル) /