rubygdbm

Get index of database iteration on ruby


I'm trying to iterate through database file with gdbm, create objects with values I get and assign them to an array. The problem is I can't seem to get index of iteration and I need it for my array. Here is the code:

bots_directory = "../data/bots.db"

bots = Array.new

GDBM.new(bots_directory).each_pair.with_index do |nickname, password, index|
   bots[index] = Bot.new(nickname, password)
end

Error I get:

`[]=': no implicit conversion from nil to integer (TypeError)

Also, will database file close after the block is executed?


Solution

  • I would use each_with_index instead of each_pair.with_index:

    bots_directory = "../data/bots.db"
    bots = []
    
    GDBM.new(bots_directory).each_with_index do |(nickname, password), index|
      bots[index] = Bot.new(nickname, password)
    end
    

    Or even simpler, since the index starts from 0 and increases by 1 anyway:

    bots_directory = "../data/bots.db"
    bots = []
    
    GDBM.new(bots_directory).each_pair do |nickname, password|
      bots << Bot.new(nickname, password)
    end
    

    Perhaps map is also an option?

    bots_directory = "../data/bots.db"
    
    bots = GDBM.new(bots_directory).map do |nickname, password|
      Bot.new(nickname, password)
    end