DEV Community

Cover image for Mastering Ruby Arrays
Eric The Coder
Eric The Coder

Posted on

Mastering Ruby Arrays

If you like this post and want more follow me on Twitter: Follow @justericchapman

Ruby Array declaration & access

# 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
Enter fullscreen mode Exit fullscreen mode

Ruby Array methods

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']
Enter fullscreen mode Exit fullscreen mode

Array Map, Select, Detect, Reduce and Count

#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
Enter fullscreen mode Exit fullscreen mode

Array +, -, &, |

# 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]
Enter fullscreen mode Exit fullscreen mode

If you like this post and want more follow me here on dev.to or on Twitter: Follow @justericchapman

Top comments (4)

Collapse
 
codeandclay profile image
Oliver

As well as concatinating an array with + you can use - to show you the difference.

[1,2,3,4,5] - [3,4,5] #[1, 2]
Enter fullscreen mode Exit fullscreen mode

& returns the intersection of two arrays. (Items that both arrays contain.)

[1,2,3,4,5] & [4,5,6,7] #[4, 5]
Enter fullscreen mode Exit fullscreen mode

| returns a union. (A combination of both arrays without duplicates.)

[1,2,3,4] | [1,2,3,5] #[1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Also, the constructor takes a block -- which can be handy.

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

Array.new(3) { [*1..100].sample } #[24, 61, 76]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ericchapman profile image
Eric The Coder

Thanks a million, I just update the post! I did not even know the union and intersection exist! After 2 years of Ruby I am still impress how easy it is compare to other programming language.

Those are powerful and complex Array operators but Ruby make those so easy to use.

Collapse
 
codeandclay profile image
Oliver

Yes, handling strings and collections in Ruby is a breeze. Those methods are ones I use often so were off the top of my head.

Collapse
 
tax79 profile image
tax79 • Edited

There is a mistake:

fruits.each do { |fruit| puts fruit }
Enter fullscreen mode Exit fullscreen mode

Should be

fruits.each { |fruit| puts fruit }
Enter fullscreen mode Exit fullscreen mode

Same on this page:
dev.to/ericchapman/my-beloved-ruby...