Skip to main content
Ruby Language:

Ruby's Array() and Array.wrap

17

Episode 305 · July 30, 2019

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

ruby


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
Transcripts

No transcripts available. Earn a free month

Loading...

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.