Introduction
Map (also called collect) helps you change each item in a list to something new, making a new list with these changed items.
new_array = old_array.map { |item| transformation }numbers = [1, 2, 3] doubled = numbers.map { |n| n * 2 } # doubled is [2, 4, 6]
words = ["cat", "dog"] lengths = words.map { |w| w.length } # lengths is [3, 3]
names = ["Alice", "Bob"] greetings = names.map { |name| "Hello, #{name}!" } # greetings is ["Hello, Alice!", "Hello, Bob!"]
fruits = ["apple", "banana", "cherry"] uppercase_fruits = fruits.map { |fruit| fruit.upcase } puts uppercase_fruits
map (or collect) do to an array?mapmap method takes each item in the array and applies the block's code to it.map[1, 2, 3] using map?map uses a block with { |variable| code } or do |variable| code end.{ |x| x * 2 }. Others have syntax errors or wrong block format.[4, 5, 6].map { |n| n + 1 }mapmap method returns a new array with these values: [5, 6, 7].numbers = [1, 2, 3]
numbers.map { n n * 2 }{ |n| n * 2 }.["apple", "banana", "cherry"], how do you use map to create a new array with the length of each string?fruit.length inside the block.map with correct blockmap { |fruit| fruit.length } returns a new array of lengths.Pass the test and this pattern moves unknown