Ruby/Array/map

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Array map with regular expression

[1,2].map{|x| /#{x}/}   # => [/1/, /2/]
[1,2].map{|x| /#{x}/o}  # => [/1/, /1/]



Change array elements with map!

array = ["a", "b", "c"]
array.map! { |x| x.downcase }
p array                               # => ["a", "b", "c"]



Map to uppercase

words = %w[hello world]                 # Another collection
upper = words.map {|x| x.upcase }       # Map to uppercase



The map method returns a new array instead of a string.

month_a = %w[ nil jan feb mar apr may jun jul aug sep oct nov dec ]
month_a_2007 = month_a.map { |e| e.capitalize + " 2007" }