Array-Giving Enumerables!!! [Ruby Programming Language Notes]
- array.map–allows us to take in an array and modify it a certain way. (Returns a new array!)
- (This can let us skip the step of shoveling a desired result into a new array[].)
- arr = [“a”, “b”, “c”, “d”]
- Old way:
- new_arr = [ ]
- arr.each { |ele| new_arr << ele.upcase + “!” }
- print new_arr
- puts
- Output:
- [“A!”, “B!”, “C!”, “D!”]
- New way with .map:
- arr = [“a”, “b”, “c”, “d”]
- #(.map is still an enumerable, so when we call it we have to pass in a block.)
- #This block accepts the element as well, like .each.
- new_arr = arr.map { |ele| ele.upcase + “!” }
- #In the block parameter directly above, ‘|ele|‘ is the original element; ‘ele.upcase + “!”‘ is the code inside the block that we want the new element to become. ‘.map‘ takes this code, or expression, and evaluates it to new string which becomes a new element of the array.
- print new_arr
- puts
- Output:
- [“A!”, “B!”, “C!”, “D!”]
- .map automatically sets up the new array & shovels into it!
- Essentially, we’re “mapping” elements of the original array through the block to get a new array.
- .map evaluates to (returns) a new array!
- array.select–allows us to take elements of an array, based on the criteria (code) we specify. (Returns an array!)
- The “criteria (code)” must be a boolean value for .select to work, which makes sense if we think about it. When “true” we take the element, and when “false” we don’t take the element.
- Old way:
- nums = [1,2,3,4,5,6]
- evens = [ ]
- nums.each do |num|
- if num % 2 == 0
- evens << num
- end
- if num % 2 == 0
- end
- print evens
- puts
- Outputs: [2,4,6]
- *Essentially, we are “selecting” elements of an array based on the criteria we specify!
- .select evaluates, or returns, to a new array!
We can also do .map.with_index. This would pass the element & the index, of course!