Understanding Data Streams

Introduction: Understanding Data Streams

Welcome to the lesson on data streams. Data streams represent continuous datasets, much like data received in real-time from a weather station or a gaming application.

In this lesson, we will explore handling these data streams, learning to access elements, slice segments, and convert these streams into strings for better comprehension.

Representing Data Streams in Ruby

In Ruby, data streams are typically represented using arrays, with each element potentially being a hash to store structured data.

Let's create a simple Ruby class named DataStream. This class will encapsulate operations related to data streams in our program:

Ruby
class DataStream
  def initialize(data)
    @data = data
  end
end

To use it, we instantiate a DataStream object with an array, where each element is a hash:

Ruby
stream = DataStream.new([
  { id: 1, value: 100 },
  { id: 2, value: 200 },
  { id: 3, value: 300 },
  { id: 4, value: 400 }
])

Accessing Elements - Key Operation

To access individual elements in a data stream, indexing is commonly used. The get method shown below fetches the i-th element from the data stream:

Ruby
class DataStream
  def initialize(data)
    @data = data
  end

  def get(i)
    @data[i]
  end
end

Here's how you use the get method:

Ruby
stream = DataStream.new([
  { id: 1, value: 100 },
  { id: 2, value: 200 },
  { id: 3, value: 300 },
  { id: 4, value: 400 }
])

puts stream.get(2)  # Outputs: {:id=>3, :value=>300}
puts stream.get(-1) # Outputs: {:id=>4, :value=>400}

In this example, stream.get(2) retrieves {:id=>3, :value=>300}, the third element (since indexing starts from 0). Meanwhile, stream.get(-1) retrieves the last element, {:id=>4, :value=>400}. In Ruby, you can also access the first and last elements in an array directly using .first and .last.

Slicing - A Useful Technique

Slicing retrieves a range of elements rather than a single one. The slice method creates a new array containing elements from position i to j (inclusive) in the data stream:

Ruby
class DataStream
  def initialize(data)
    @data = data
  end

  def get(i)
    @data[i]
  end

  def slice(i, j)
    @data[i..j]
  end
end

Here's how you use the slice method:

Ruby
stream = DataStream.new([
  { id: 1, value: 100 },
  { id: 2, value: 200 },
  { id: 3, value: 300 },
  { id: 4, value: 400 }
])

puts stream.slice(1, 3)  # Outputs: [{:id=>2, :value=>200}, {:id=>3, :value=>300}, {:id=>4, :value=>400}]

In this example, stream.slice(1, 3) retrieves an array with the elements at positions 1 to 3.

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