0
0
Rubyprogramming~5 mins

Map/collect for transformation in Ruby

Choose your learning style9 modes available
Introduction
Map (also called collect) helps you change each item in a list to something new, making a new list with these changed items.
When you want to add 1 to every number in a list.
When you want to turn a list of names into a list of greetings.
When you want to get the length of each word in a list.
When you want to change all temperatures from Celsius to Fahrenheit.
When you want to make all words uppercase in a list.
Syntax
Ruby
new_array = old_array.map { |item| transformation }
You can also use 'collect' instead of 'map'; they do the same thing.
The block inside curly braces { } tells Ruby how to change each item.
Examples
Multiply each number by 2.
Ruby
numbers = [1, 2, 3]
doubled = numbers.map { |n| n * 2 }
# doubled is [2, 4, 6]
Get the length of each word.
Ruby
words = ["cat", "dog"]
lengths = words.map { |w| w.length }
# lengths is [3, 3]
Make a greeting for each name.
Ruby
names = ["Alice", "Bob"]
greetings = names.map { |name| "Hello, #{name}!" }
# greetings is ["Hello, Alice!", "Hello, Bob!"]
Sample Program
This program changes all fruit names to uppercase and prints the new list.
Ruby
fruits = ["apple", "banana", "cherry"]
uppercase_fruits = fruits.map { |fruit| fruit.upcase }
puts uppercase_fruits
OutputSuccess
Important Notes
Map does not change the original list; it makes a new one.
You can use map with any kind of list, like numbers, words, or objects.
If you want to change the original list, use map! with an exclamation mark.
Summary
Map/collect changes each item in a list and returns a new list.
Use a block to tell Ruby how to change each item.
Original list stays the same unless you use map!.