title: Ruby - elegantly convert variable to an array if not an array already
body: <p>Given an array, a single element, or nil, obtain an array - the latter two being a single element array and an empty array respectively.</p>
  
  <p>I mistakenly figured Ruby would work this way:</p>
  
  <pre><code>[1,2,3].to_a  #= [1,2,3]     # Already an array, so no change
  1.to_a        #= [1]         # Creates an array and adds element
  nil.to_a      #= []          # Creates empty array
  </code></pre>
  
  <p>But what you really get is:</p>
  
  <pre><code>[1,2,3].to_a  #= [1,2,3]         # Hooray
  1.to_a        #= NoMethodError   # Do not want
  nil.to_a      #= []              # Hooray
  </code></pre>
  
  <p>So to solve this, I either need to use another method, or I could meta program by modifying the to_a method of all classes I intend to use - which is not an option for me.</p>
  
  <p>So a Method it is:</p>
  
  <pre><code>result = nums.class == "Array".constantize ? nums : (nums.class == "NilClass".constantize ? [] : ([]&lt;&lt;nums))
  </code></pre>
  
  <p>The problem is that it is a bit of a mess. Is there an elegant way of doing this? (I would be amazed if this is the Ruby-ish way to solve this problem)</p>
  
  <hr>
  
  <h2>What applications does this have? Why even convert to an array?</h2>
  
  <p>In Rails' ActiveRecord, calling say, <code>user.posts</code> will either return an array of posts, a single post, or nil. When writing methods which work on the results of this, it is easiest to assume that the method will take an array, which may have zero, one, or many elements. Example method:</p>
  
  <pre><code>current_user.posts.inject(true) {|result, element| result and (element.some_boolean_condition)}
  </code></pre>