Welcome! Today, we’ll explore Data Transformation Techniques in Ruby, with a focus on the map
method.
Data transformation is a powerful technique for reshaping and modifying data. In this lesson, we’ll learn how to apply transformations to create new data views and how to combine transformations with filtering to extract meaningful insights.
Let’s dive in!
Data transformation is all about applying a function to each element in a dataset to reshape or modify it. In Ruby, the map
method is a great tool for this. It applies a given transformation to every element in an array, returning a new array with the modified elements.
For example, let’s use map
to find the square of each number in an array:
Ruby1numbers = [1, 2, 3, 4, 5] # our data stream 2 3# map applies the transformation to each number in the array 4squared_numbers = numbers.map { |n| n * n } 5 6puts squared_numbers # prints: [1, 4, 9, 16, 25]
Here, map
iterates over each element in numbers
and applies { |n| n * n }
, transforming each number by squaring it.
The map
method can also work with other types of data, like strings. Here’s how it can transform an array of sentences to lowercase:
Ruby1sentences = ["HELLO WORLD", "RUBY IS FUN", "I LIKE PROGRAMMING"] 2 3# map applies the `downcase` transformation to each string in the array 4lower_sentences = sentences.map { |sentence| sentence.downcase } 5 6puts lower_sentences # prints: ["hello world", "ruby is fun", "i like programming"]
In this example, map
applies downcase
to each sentence, creating a new array with all lowercase sentences.
In the previous lesson, we learned how to filter data with select
. When we combine select
with map
, we can first filter out unwanted elements and then transform the remaining data, all in a single line.
Let’s say we have an array of sentences, and we only want sentences containing the word "RUBY" converted to lowercase:
Ruby1sentences = ["HELLO WORLD", "RUBY IS FUN", "I LIKE PROGRAMMING"] 2 3# First, we filter with select, then transform with map 4filtered_lowercase_sentences = sentences 5 .select { |sentence| sentence.include?("RUBY") } 6 .map { |sentence| sentence.downcase } 7 8puts filtered_lowercase_sentences # prints: ["ruby is fun"]
In this example, select
filters the sentences to include only those containing "RUBY". Then, map
converts each selected sentence to lowercase, resulting in a clear, transformed view of our data.
Congratulations! You’ve learned the fundamentals of Data Transformation in Ruby. We covered how to reshape data using the map
method, how to perform transformations flexibly, and how to combine transformations with filtering for advanced data manipulation.
These skills are foundational for data processing, helping you clean and reshape data with ease. Now, try out these concepts with the practice exercises that follow. Happy coding and transforming!