DEV Community

Cover image for Level Up Your Ruby Skillz: Working With Arrays

Level Up Your Ruby Skillz: Working With Arrays

Molly Struve (she/her) on May 08, 2019

When I first started out, there was a senior engineer that I worked with who was a wizard when it came to working with arrays. He taught me all the...
Collapse
 
kdraypole profile image
Kobe Raypole

Awesome article! I use the with_index method quite often. Another option is each_with_index.

At first, there appears to be no difference until you take into account that with_index accepts an optional "start index". Therefore you can start your array index at 1 by doing

result = ['a', 'b', 'c'].map.with_index(1) do |letter, index|
  "#{letter}:#{index}"
end
# result = ["a:1", "b:2", "c:3"]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
molly profile image
Molly Struve (she/her)

WHAT?!!!!!! I had no clue, thank you for sharing!!!

Collapse
 
danazar96 profile image
Aidan Walters-Williams • Edited

Fantastic article Molly! I have been using

result = [1, 2, 3].map do |number|
  ['a', 'b', 'c'].map do |letter|
    "#{number}:#{letter}"
  end
end
result.flatten

for ages without knowing there was a better alternative!

Collapse
 
ludamillion profile image
Luke Inglis

Guess it pays to keep a beginner's mind. I've been using Ruby professionally for 7+ years and some of these were new to me.

Collapse
 
tadman profile image
Scott Tadman • Edited

They keep adding new toys to the language. One of my more recent discoveries is transform_keys and transform_values for Hash which they shipped without fanfare in Ruby 2.4. That's proven really valuable for "symbolizing" keys and cleaning up values.

Collapse
 
lennythedev profile image
Lenmor Ld

Nice! As a beginner in Ruby, this is really helpful.
The thing that always trips me up is forgetting the | to surround the current element and using ( instead of {
I keep thinking like ES6 in Ruby 😳

Collapse
 
grsahil20 profile image
Sahil

Additional Bonus for you flatten. Flatten, as name suggests flatten out an array no matter how much nesting level is involved for an array. Below is the example for 3 level nesting

a =  [[1, 2, 3], [4, [5, [6, 7]]]]
b = a.flatten
# b = [1, 2, 3, 4, 5, 6, 7]

Also, you can do a.flatten!, which will overwrite a itself and assign the new value.

a =  [[1, 2, 3], [4, [5, [6, 7]]]]
a.flatten!
# a = [1, 2, 3, 4, 5, 6, 7]
Collapse
 
lukewduncan profile image
Luke Duncan • Edited

Thanks for the awesome article Molly! I found it very helpful, the examples are clear and concise!

I've created a short cheatsheet on a Paper doc so people can keep it handy: paper.dropbox.com/doc/Ruby-Array-M...

Collapse
 
molly profile image
Molly Struve (she/her)

Wow, this is really fantastic! Thank you for putting that together. I will keep this in mind for future posts.

Do you mind if I add a link to your cheatsheet at the bottom of the post and share it on Twitter? I think people will find it very useful and I will definitely be sure to give you credit for it.

Collapse
 
lukewduncan profile image
Luke Duncan

Of course! After all, it is your work!!!

Collapse
 
botanical profile image
Jennifer Tran

I've used some of these methods before but it was great to learn new ones such as detect and reject! I also never realized that some of these methods return the original array. Thank you for pointing that out and thank you for such a great tutorial!

Collapse
 
aritdeveloper profile image
Arit Developer

What I LOVE about this tutorial, Molly, is how you include examples of how you used to code, before becoming proficient at these different methods. I laughed at each "newbie example" you gave, cos that's exactly how I've been doing things too! LOL. Thank you for this awesome resource!

Collapse
 
molly profile image
Molly Struve (she/her)

We all gotta start somewhere 😃

Collapse
 
swiknaba profile image
Lud

For single methods without argument, you can use shorthand syntax (aka. "passing a proc"):

[1, 2, 3, 4].count(&:even?)
# => 2
Collapse
 
codeandclay profile image
Oliver

You can also define your own methods and do something similar using &method.

def dog?(animal)
  ["spaniel", "schnauzer"].include? animal
end  
["perch", "spaniel", "haddock", "schnauzer", "cod"].count(&method(:dog?))
#=> 2
Collapse
 
tadman profile image
Scott Tadman

A lot of these convenience methods work on any Enumerator, and a lot of things emit those. You can even write your own with a few lines of code.

Collapse
 
molly profile image
Molly Struve (she/her)

YES! One of my favorite ruby methods currently is to_enum so you can use all these convenience methods with your own.

I originally had this post titled "Level Up Your Ruby Skillz: Working with Enumerators" but wanted to make it very approachable to new devs learning Ruby and figured starting with straight Arrays would be better.

Thread Thread
 
tadman profile image
Scott Tadman • Edited

I didn't know about the buddy method enum_for which also looks super handy.

Everything in Ruby is an object, but maybe we should also say that everything, with the right attitude (or method call!), can be an Enumerator, too.

Collapse
 
bengreenberg profile image
Ben Greenberg

This is such a useful reference! Thank you for this, it's always great to be reminded how awesome Ruby is! 💙

Collapse
 
yechielk profile image
Yechiel Kalmenson

Ruby's plethora of built-in array methods of one of the best things about the language!

Thanks for this round up ❤️

Collapse
 
andresshare profile image
Andrés

Thanks MOLLY for sharing it was very useful to me :)

Collapse
 
wesonweb profile image
Wes

Brilliant article and really useful resource to keep coming back to. Thank you!