All Lessons / Ruby's Array() and Array.wrap

Ruby's Array() and Array.wrap

#305 ยท July 30, 2019

Your Teacher | Chris Oliver

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

Discussion

Loading...
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.