Filtering Data Streams

Diving Into Filtering Data Streams

Welcome to our hands-on tutorial on data filtering in Ruby.

Filtering is a fundamental skill in programming that lets us focus on specific data we care about while discarding the rest. By filtering, we can extract only the data that meets certain criteria, making it easier to work with relevant information.

Understanding Filtering in Programming

Data filtering in programming is similar to filtering options on a shopping website. Imagine you’re looking for a specific shirt online. You can filter by color, size, brand, and other attributes. In programming, our data items are like those shirts, and our filtering criteria serve as conditions that decide which items pass through.

Filtering Data Using Loops

Loops allow us to repeat actions on each element in a data stream, making them useful for filtering. In Ruby, we can use the each loop to examine each element against certain criteria.

For instance, let’s filter out numbers less than ten from an array:

Ruby
def filter_with_loops(data_stream)
  filtered_data = []
  data_stream.each do |item|
    filtered_data << item if item < 10
  end
  filtered_data
end

In this example, the each loop checks each item, and if it’s less than ten, it adds it to the filtered_data array.

Using the select Method for Filtering

Ruby provides a select method specifically for filtering. With select, we can pass a condition block to filter elements in a simpler and more readable way.

Here’s how we could rewrite the previous example using select:

Ruby
def filter_with_select(data_stream)
  data_stream.select { |item| item < 10 }
end

Here, { |item| item < 10 } is the condition that select uses to filter elements in data_stream.

Combining Multiple Conditions with && and ||

In some cases, you may want to filter elements based on more than one condition. In Ruby, we can use && (AND) and || (OR) to combine conditions.

For example, let’s filter for numbers that are both less than ten and even:

Ruby
data_stream = [23, 5, 7, 12, 19, 2]

filtered_data = data_stream.select { |item| item < 10 && item.even? }
puts filtered_data # Output: [2]

In this example, only the numbers that are both less than ten and even pass through the filter.

Alternatively, let’s say we want numbers that are either less than ten or greater than twenty:

Ruby
filtered_data = data_stream.select { |item| item < 10 || item > 20 }
puts filtered_data # Output: [5, 7, 2, 23]

Here, numbers satisfying either condition (less than ten or greater than twenty) are included in the output.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal