我正在尝试创建一个基于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
答案 0 :(得分: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?
会返回true
或false
,因此您无需将其返回值与true
和false
进行比较,只需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