从select中删除哈希项

时间:2022-07-18 00:53:30

Is there a way to delete a hash item from within a select? I want to check if a file exists in a directory and if it does, remove it from the hash.

有没有办法从选择中删除哈希项?我想检查目录中是否存在文件,如果存在,则将其从哈希中删除。

hash = {"http://s3-us-west-2.amazonaws.com/packages/ics/ics_4.0.0.tar.gz"=>"5103909285b549eda0b6a13dd503790a", ...}

hash.select do |k,v|
  if File.file?("#{k[/[^\/]+$/]}")
    # Remove from hash

  end
end

1 个解决方案

#1


You cannot delete element in select, delete_if is a good choice.

你不能删除select中的元素,delete_if是个不错的选择。

hash.delete_if { |k,_| File.file?("#{k[/[^\/]+$/]}") }

update:

hash_copy = hash.dup

hash.select do |k,v|
  if File.file?("#{k[/[^\/]+$/]}")
    hash_copy.delete(k)
    ......
  end
end

#1


You cannot delete element in select, delete_if is a good choice.

你不能删除select中的元素,delete_if是个不错的选择。

hash.delete_if { |k,_| File.file?("#{k[/[^\/]+$/]}") }

update:

hash_copy = hash.dup

hash.select do |k,v|
  if File.file?("#{k[/[^\/]+$/]}")
    hash_copy.delete(k)
    ......
  end
end