简体   繁体   English

获取在ruby上的数据库迭代索引

[英]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. 我正在尝试使用gdbm遍历数据库文件,使用获取的值创建对象,并将其分配给数组。 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? 另外,执行该块后数据库文件是否会关闭?

I would use each_with_index instead of each_pair.with_index : 我将使用each_with_index而不是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: 甚至更简单,因为索引从0开始,反正增加1

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? 也许map也是一种选择?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM