Mastering Ruby Arrays
Tags: ruby, rails, beginners, tutorial
Published: 2021-03-30 10:00:27

---
title: Mastering Ruby Arrays
published: true
description: 
tags: ruby, rails, beginner, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/m2ccmtqagomshkp8yye2.jpg
---

If you like this post and want more follow me on Twitter: <a href="https://twitter.com/justericchapman?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @justericchapman</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<h2>Ruby Array declaration & access</h2>
```ruby
# Array declaration
fruits = ['Apple', 'Orange', 'Banana']
fruits = %w(Apple Orange Banana) 

# Array constructor
Array.new(3) #[nil, nil, nil]

# Fill with random numbers
Array.new(3) { [*1..100].sample } #[24, 61, 76]

fruits.length # 3

# Array direct access
fruits.first  # Apple
fruits.last   # Banana

# Array direct access by position number (zero base)
fruits[0]     # Apple
fruits[-2]    # Orange
fruits[3]     # nil
fruits[1..2]  # ['Orange', 'Banana']

# iteration
fruits.each do { |fruit| puts fruit } 

fruits.each_with_index do |fruit, index|
  puts fruit  # Apple
  puts index  # 0
end
```

<h2>Ruby Array methods</h2>
```ruby
fruits.include? 'Orange'  # true
[1, 5, 2, 4, 3].sort  # [1, 2, 3, 4, 5]
[1, 2, 3].reverse  # [3, 2, 1]

fruits.push 'Strawberry' # append at the end
fruits <<  'Raspberry' # append at the end
fruits.unshift 'Strawberry' # Append in front

fruits.pop # remove last
fruits.delete_at(0) # remove first element
fruits.shift  # remove the first element

# split a string into an array
'Apple Orange Banana'.split ' '  #['Apple', 'Orange', 'Banana']

# Join array into a string 
fruits.join ', '  # 'apple, orange, banana'

# Add in a new array
array1 = %w(dog cat bird)
array2 = %w(fish hamster)
array3 = array1 + array2 #['dog', 'cat', 'bird', 'fish', 'hamster']

# Concat in the same array
array1.concat array2 
puts array1  #['dog', 'cat', 'bird', 'fish', 'hamster']

# Constructing arrays with * splat operator
puts ['dog', *array2, 'bird']  #['dog', 'fish', 'hamster', bird']

#convert to array
(1..10).to_a  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
('a'..'e').to_a # ['a', 'b', 'c', 'd', 'e']
```

<h2>Array Map, Select, Detect, Reduce and Count</h2>
```ruby
#map (return a modified array)
names = ['paul', 'john', 'peter']
names_capitalize = names.map do |name|
  name.capitalize
end
# ['Paul', 'John', 'Peter']

# short hand version
names_capitalize = names.map { |name| name.capitalize }

# Symbol to proc
names_capitalize = names.map &:capitalize

#select (return all match)
products = [
  { name: 'Mac Book Pro', active: true, price: 1599.99 },
  { name: 'iWatch', active: false, price: 599.99 },
  { name: 'iPad Pro', active: true, price: 699.99 },
]
active_products = products.select { | product | product[:active] }

#Detect (return first match)
first_active_product = products.detect { | product | product[:active] }

# Reduce (return one)
total = products.reduce(0) do |total, product| 
  total = total + product[:price]
end
puts total  # 2899.97

# Count (return array count)
nb_products = products.count { |product| product.price > 1000 }
puts nb_products # 1
```

<h2>Array +, -, &, |</h2>
```ruby
# Concat
[1, 2, 3] + [4, 5] #[1, 2, 3, 4, 5]

# Difference
[1,2,3,4,5] - [3,4,5] #[1, 2]

# Intersection (Items that both arrays contain)
[1,2,3,4,5] & [4,5,6,7] #[4, 5]

# Returns a union. (A combination of both arrays without duplicates
[1,2,3,4] | [1,2,3,5] #[1, 2, 3, 4, 5]
```

If you like this post and want more follow me here on dev.to or on Twitter: <a href="https://twitter.com/justericchapman?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @justericchapman</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>