在Ruby中删除数组中的空位置

时间:2016-03-21 22:55:18

标签: arrays ruby hash hashmap

我创建了以下方法:

def list_all_keys
$hash_table
keys=[]
output_file = File.open("output.txt", "w")
output_file.write("Hash Table: \n")
for i in 0..$hash_table.length - 1
  current_node = $hash_table[i]
  puts current_node.val
  while current_node.val != -1
    keys.push("key:" + current_node.key.to_s + ", value:" + current_node.val.to_s + ". pos:" + current_node.pos.to_s)
    current_node = current_node.next
  end
  puts "Hash:" + i.to_s + ", Entries:" + keys.to_s
  output_file.write("Hash:" + i.to_s + ", Entries:" + keys.to_s + "\n")
  keys = []
end
output_file.close
end
end

要编写一个文件output.txt,其中包含所有值的哈希映射,但我的输出包含很多空位(因为我认为是while循环)。

输出示例:

Hash:3964, Entries:[]    /// CAN THESE BE PREVENTED? ///
Hash:3965, Entries:["key:quicker., value:1. pos:[3573]"]
Hash:3966, Entries:["key:easily, value:2. pos:[5639, 10510]"]
Hash:3967, Entries:["key:kept, value:6. pos:[1732, 1785, 3392, 5932, 7544, 9047]"]
Hash:3968, Entries:[]
Hash:3969, Entries:[]

有什么方法可以阻止这种情况吗?

1 个答案:

答案 0 :(得分:0)

在您的puts "Hash" ...行之前,您可以撰写next if keys.empty?;

这将跳到循环的下一次迭代。

顺便说一下,如果要删除数组中的任何nil元素,可以使用flatten

即。 [nil, 2, 3, nil ].flatten将等于[2,3]