Ruby's Array() and Array.wrap

#305 ยท July 30, 2019

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, 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


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, :+)

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 72,152+ developers who get early access to new tutorials, screencasts, articles, and more.

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.