Leonko
Leonko

Reputation: 139

Using an Enumerator instead of loops

I usually use loop as below to request data form an external API or DB (redis pop):

records = []
loop do
  record = MyHandler.new(token).fetch
  break unless record
  records.push(record)
end

It works, but to make it look better, I wonder whether there is any way to use an Enumerator. Does anyone know one?

Upvotes: 0

Views: 87

Answers (4)

Stefan
Stefan

Reputation: 114138

Wrapping your code in an Enumerator is quite easy:

record_enumerator = Enumerator.new do |y|
  loop do
    record = MyHandler.new(token).fetch
    break unless record
    y << record
  end
end

You can now iterate over the records using a block:

record_enumerator.each { |record|
   # do something with record
}

Or fetch all records with:

records = record_enumerator.to_a

If MyHandler is your class, you could implement MyHandler#each instead and include Enumerable.

Upvotes: 5

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

If you are looking for the really short syntax, here you go:

records << record while record = MyHandler.new(token).fetch

It will work like a charm, the condition check is done before executing the loop body, hence record is always initialized.

Upvotes: 0

bundacia
bundacia

Reputation: 1036

How about this?

while(record = MyHandler.new(token).fetch)
  records.push(record)
end

That gets rid of the ugly loop/break logic.

Alternatively, you could create an ennumerable object instead of using the records array:

class RecordList
  include Enumerable

  attr :token

  def initialize(token)
    @token = token
  end

  def each
    MyHandler.new(token).fetch
  end
end

records = RecordList.new token

Upvotes: 2

Cereal
Cereal

Reputation: 3829

You can use while loops in ruby like so:

records = []
record = MyHandler.new(token).fetch
while record do
    records << record
    record = MyHandler.new(token).fetch
end

There might be an even more elegent way, but from the information provided, that's the best I can come up with.

Upvotes: 0

Related Questions