DEV Community

Andy Huynh
Andy Huynh

Posted on • Edited on

1

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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay