使用正则表达式对哈希进行线分割

问题描述 投票:1回答:1

我试图在ubuntu中创建一个基于文件/etc/mime.types的哈希,例如,它将白色空间上的每一行和“非单词”正则表达式搜索分开。以下是我的代码。但我不能让它正确输出零值的。他们把所有其他东西放在一起,但是如果你用pp打印它们,有些人会回复为零。有什么建议?

#!/usr/bin/ruby
mime = Hash.new()

File.open("/etc/mime.types", "r") do |file|
  file.each_line do |line|
    next if line[0] == ?#
    next if line == "\n"
    key, value = line.chomp.split(/\W+\s/)
    mime[key] = value
  end
end

if (mime.has_value?('nil') == true)
    mime.sort.each {|key,value| puts "#{key} has no extensions."}
elsif(mime.has_value?('nil') == false)
    mime.sort.each {|key, value| puts "#{key} has extensions #{value}"}
end

这只是输出的尾端,因为它在执行时位于前面,所以最容易看到

我预计

video/quicktime has extensions qt mov
**video/vnd.fvt has no extensions** 
**video/vnd.motorola.video has no extensions 
video/vnd.motorola.videop has no extensions** 
video/vnd.mpegurl has extensions mxu
**video/vnd.mts has no extensions no**
video/vnd.nokia.interleaved-multimedia has extensions 
**video/vnd.vivo has no extensions** 
video/x-flv has extensions flv
video/x-la-asf has extensions lsf lsx
video/x-matroska has extensions mpv mkv
video/x-mng has extensions mng
video/x-ms-asf has extensions asf asx
video/x-ms-wm has extensions wm
video/x-ms-wmv has extensions wmv
video/x-ms-wmx has extensions wmx
video/x-ms-wvx has extensions wvx
video/x-msvideo has extensions avi
video/x-sgi-movie has extensions movie
x-conference/x-cooltalk has extensions ice
x-epoc/x-sisx-app has extensions sisx
x-world/x-vrml has extensions vrm vrml wrl

但我明白了

video/quicktime has extensions qt mov
video/vnd.fvt has extensions 
video/vnd.motorola.video has extensions 
video/vnd.motorola.videop has extensions 
video/vnd.mpegurl has extensions mxu
video/vnd.mts has extensions 
video/vnd.nokia.interleaved-multimedia has extensions 
video/vnd.vivo has extensions 
video/x-flv has extensions flv
video/x-la-asf has extensions lsf lsx
video/x-matroska has extensions mpv mkv
video/x-mng has extensions mng
video/x-ms-asf has extensions asf asx
video/x-ms-wm has extensions wm
video/x-ms-wmv has extensions wmv
video/x-ms-wmx has extensions wmx
video/x-ms-wvx has extensions wvx
video/x-msvideo has extensions avi
video/x-sgi-movie has extensions movie
x-conference/x-cooltalk has extensions ice
x-epoc/x-sisx-app has extensions sisx
x-world/x-vrml has extensions vrm vrml wrl
ruby hash line split
1个回答
5
投票

字符串'nil'和对象nil不是一回事。你的mime.has_value?('nil')问哈希,如果它的一个值是字符串'nil',而不是对象nil。你(想你)想要这个:

if(mime.has_value?(nil))
  mime.sort.each {|key,value| puts "#{key} has no extensions."}
else
  mime.sort.each {|key, value| puts "#{key} has extensions #{value}"}
end

并且has_value?返回truefalse所以你不需要将它的回报值与truefalse进行比较,只需if(mime.has_value?(nil)) ... else即可。

但那仍然不会给你你想要的东西。您的if将声称所有密钥都没有扩展,如果其中至少有一个没有扩展且没有多大意义。你想用这样的东西迭代mime

mime.each do |k, v|
  if(v.nil?)
    puts "#{k} has no extensions"
  else
    puts "#{k} has extensions #{v}"
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.