Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

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]]
  • + Share This
  • 🔖 Save To Your Account