␡
- Slicing an Array
- Iterating over an Array
- Creating Enumerable Classes
- Sorting an Array
- Iterating over Nested Arrays
- Modifying All the Values in an Array
- Sorting Nested Arrays
- Building a Hash from a Config File
- Sorting a Hash by Key or Value
- Eliminating Duplicate Data from Arrays (Sets)
- Working with Nested Sets
This chapter is from the book
Modifying All the Values in an Array
Array#collect, also known as Array#map, is used to modify the values of an Array and return a new array.
['This', 'is', 'a', 'test!'].collect do |word| word.downcase.delete '^A-Za-z' end #=> ["this", "is", "a", "test"]
If you want to do this on a nested Array, you need something a little stronger:
class Array def collect_recur(&block) collect do |e| if e.is_a? Array e.collect_recur(&block) else block.call(e) end end end end [[1,2,3],[4,5,6]].collect_recur { |elem| elem**2 } #=> [[1, 4, 9], [16, 25, 36]]