Ruby's Array() and Array.wrap

July 30, 2019

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Learn how to remove conditionals and make your code simpler and more reliable using Ruby and ActiveSupport's Array wrap methods

Notes

Array([1,2,3]) #=> [1,2,3]
Array(1) #=> [1]
Array(nil) #=> []
Array(a: 1, b: 2) #=> [[:a, 1], [:b, 2]]
require 'active_support/all'

Array.wrap([1,2,3]) #=> [1,2,3]
Array.wrap(1) #=> [1]
Array.wrap(nil) #=> []
Array.wrap(a: 1, b: 2) #=> [{a: 1, b: 2}]
def sum(numbers)
  Array.wrap(numbers).inject(0, :+)
end

p sum([1,2,3]) #=> 6
p sum(1) #=> 1
p sum(nil) #=> 0

Want to stay up-to-date with Ruby on Rails?

Join 86,796+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.