[英]Remove empty positions in array in Ruby
I've created the following method:我创建了以下方法:
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
To write a file output.txt
which would contain a hash map of all the values but my output includes a lot of empty positions (because of the while loop, I think).编写一个文件
output.txt
,其中将包含所有值的哈希映射,但我的输出包含很多空位置(因为我认为是 while 循环)。
Example of output:输出示例:
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:[]
Is there some way to prevent this?有什么方法可以防止这种情况吗?
Right before your puts "Hash" ...
line you can write next if keys.empty?;
就在你
puts "Hash" ...
行之前,你可以写下next if keys.empty?;
This will skip to the next iteration of the loop.这将跳到循环的下一次迭代。
By the way, if you want to remove any nil elements of an array, you can use flatten
.顺便说一下,如果你想删除数组的任何 nil 元素,你可以使用
flatten
。
Ie [nil, 2, 3, nil ].flatten
will equal [2,3]
即
[nil, 2, 3, nil ].flatten
将等于[2,3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.