简体   繁体   English

Ruby中的两个比较,除非

[英]Ruby two comparisons in unless

Im ruby beginner and very frustrated with this code: 我是红宝石初学者,对此代码感到非常沮丧:

unless ((f[-4..-5] == '.png') || (f[-4..-5] == '.jpg'))

Somehow the second comparison is not recognized by ruby! 不知何故,Ruby无法识别第二个比较! Whats wrong? 怎么了?

I think you should use f[-4..-1] instead of f[-4..-5] . 我认为您应该使用f[-4..-1]而不是f[-4..-5]

Or you can use regular expression: 或者您可以使用正则表达式:

unless f =~ /\.(png|jpg)$/

or use String#end_with? 或使用String#end_with? :

unless f.end_with?('.png', '.jpg')

f[-4..-5] would be an empty string, which will never match '.png' . f[-4..-5]将是一个空字符串,永远不会匹配'.png' So the second term of your disjunction will never be evaluated. 因此,析取的第二项将永远不会被评估。

If you are conditioning by the file extension, then you may do this: 如果您以文件扩展名为条件,则可以执行以下操作:

case File.extname(f)
when ".png", ".jpg"
else
  ...
end

How is below : 下面如何:

ext_nm = File.extname(f)
unless [".png", ".jpg"].include? ext_nm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM