Data Transformation Techniques
Introduction to Data Transformation
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!
Understanding Data Transformation with map
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:
Here, map iterates over each element in numbers and applies { |n| n * n }, transforming each number by squaring it.
Transforming Strings with map
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:
In this example, map applies downcase to each sentence, creating a new array with all lowercase sentences.
Combining map with select for Powerful Transformations
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:
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.
