Patchouli's Computatrunomicon

Search IconIcon to open search

basic-enumerable-methods

Last updated June 4, 2022.

# Metadata

2022-06-03 18:42 | basic-enumerable-methods | Doriel Rivalet

# Content

The do is optional in a for loop in Ruby and may cause issues if used in IRB

| block variable |

This is the element from your array that the block is currently iterating over. You can use any variable name that you find helpful here

For multi-line blocks, the commonly accepted best practice is to change up the syntax to use do...end instead of {...}:

#map method (also called #collect) transforms each element from an array according to whatever block you pass to it and returns the transformed elements in a new array.

its like commutativity of multiplication a*b, a being the array element and b being the block

1
item.gsub('string to change', 'string end result')

#select method (also called #filter)

#reduce is replacement for accumulator variables

#reduce method (also called #inject)

1
[1,2,3].reduce(initial_accumulator_value) {|accumulator, value| stuff}
1
2
3
4
5
6
7
votes = ["Bob's Dirty Burger Shack", "St. Mark's Bistro", "Bob's Dirty Burger Shack"]

votes.reduce(Hash.new(0)) do |result, vote|
  result[vote] += 1
  result
end
#=> {"Bob's Dirty Burger Shack"=>2, "St. Mark's Bistro"=>1}

bang methods make the methods destructive, mutates the object.

the ruby way

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
friends = ['Sharon', 'Leo', 'Leila', 'Brian', 'Arun']

def invited_friends(friends)
  friends.select { |friend| friend != 'Brian' }
end

friends
#=> ['Sharon', 'Leo', 'Leila', 'Brian', 'Arun']

invited_friends(friends)
 #=> ["Sharon", "Leo", "Leila", "Arun"]

enumerable methods are used on both arrays and hashes

Enumerable Iterators Cheat Sheet

The full list is available  in the docs here.

Awesome but less common methods

1
2
3
4
5
6
7
8
array = %w(a b c) #a word of a b and c

array.map.with_index { |ch, idx| [ch, idx] }

# [["a", 0], ["b", 1], ["c", 2]]

["11", "21", "5"].map(&:to_i)
["orange", "apple", "banana"].map(&:class)

.each{key value} .each_with_index{value key}

# Sources

Own notes

https://www.theodinproject.com/lessons/ruby-basic-enumerable-methods

https://www.rubyguides.com/2018/10/ruby-map-method/

# Content Lists

If you prefer browsing the contents of this site through a list instead of a graph, you can find content lists here too:

# Knowledge Index


Interactive Graph