- tranforming one collection into another collection
array = [1,2,3,4,5]
new_array = array.map do |number|
number * 2
end
print new_array
Will display
[2, 4, 6, 8, 10]
For strings:
job_titles = ['developer', 'analyst', 'manager', 'designer', 'engineer']
puts "\nOriginal job titles"
print job_titles
capital_job_titles = job_titles.map do |job_title|
job_title.capitalize
end
puts "\nCapitalized job titles"
print capital_job_titles
Will display
Original job titles
["developer", "analyst", "manager", "designer", "engineer"]
Capitalized job titles
["Developer", "Analyst", "Manager", "Designer", "Engineer"]
To transform an array using each we would need to build the new array.
prices = [5.50, 7.00, 6.00, 9.00, 4.50]
puts "\n\nOriginal prices"
print prices
puts "\nCalculate discounted prices using each loop"
discounted_prices = []
prices.each do |price|
discounted_prices << price - price * 0.5
end
print discounted_prices
puts "\nCalculate discounted prices using map"
discounted_prices = prices.map do |price|
price - price * 0.5
end
print discounted_prices
puts "\nCalculate discounted prices using single line map"
discounted_prices = prices.map { |price| price - price * 0.5 }
print discounted_prices
# Map can be very powerful when chained.
string_prices = ['5.50', '7.00', '6.00', '9.00', '4.50']
puts "\nConvert string prices to integer and calculate price"
discounted_prices = string_prices.map { |value| value.to_i }.map { |price| price - price * 0.5 }
print discounted_prices
Change existing array using the bang operator
array = [1,2,3,4,5]
array.map! do |number|
number * 2
end
print array
Will display
[2, 4, 6, 8, 10]