DEV Community

Andy Huynh
Andy Huynh

Posted on • Updated on

handy Ruby methods #1 - Array#compact

This is my attempt applying the 80/20 principle on Ruby methods. Here's a primer on 80/20 principle if you need a refresher.

I'll only include methods I frequent writing software at Kajabi.

An annoying error happens working with arrays. You'd assume assigning nil to an allocated array slot is okay. You're able to add it successfully.. so yeah, it must be okay! Right?

Issues pop up when you loop over an array. You'll loop over arrays plenty when dealing with real world data. Seriously, I get this error all the time.

I'd punt a baby across a football field if I never have to see this again:

NoMethodError: undefined method 'length' for nil:NilClass
Enter fullscreen mode Exit fullscreen mode

Okay, maybe not a baby, how about a terrorist? Too much? You feel my pain..

Nil guard your arrays - be better than me.

x = [1, 2, 3]
x.map { |y| y * 5 }
# [5, 10, 15]

x << nil
x << 5
# [1, 2, 3, nil, 5]

x.map { |y| y * 5 }
# NoMethodError: undefined method '*' for nil:NilClass
#    from (irb):in `block in irb_binding`
#    from (irb):in `map'

puts "ugh.. fuck me"
x.compact.map { |y| y * 5 }
# [5, 10, 15, 25]
Enter fullscreen mode Exit fullscreen mode

Keep Array#compact in your back pocket as you'll see this a lot in your software career.

Top comments (0)