Images数组Ruby检查每个值的开头



我有一组不同的图像。我试图确认,如果图像以正确的名称开头。

images = ["nginx", "help-me-1"]
images.each_with_index {|image, i| images[i].start_with?('help-me')}

不幸的是,它没有正确循环,我不确定出了什么问题。我没有收到任何类型的错误消息,我已经添加了一些日志记录,希望有一些,但没有。我可能缺少什么?

也许这就是您想要的?

if images.find?{ |image| !image.start_with?('help-me') }
#if you want to exit the app then do
abort('Dev asked to kill this app because we who knows?')
#if you want to raise exception then
raise 'Image found that does not start with help-me'
end

还是要raiseputs

images.each_with_index do |image, i| 
unless images[i].start_with?('help-me')
puts "Image #{image} at index #{i} does not start with 'help-me'"
#or raise exception here if you want
end
end

基本上,如果不是所有情况都为true,则打印一条错误消息。如果是真的,请继续。

我想最好的选择是在@Sergio Tulentsev的上面评论中。

无论如何,这只是一个进一步的想法:

images = ["nginx", "help-me-1", "flip-flop", "help-me-if-you-can", "tick-tack-toe"]
start_with_help_me = images.group_by{ |image| image.start_with?('help-me') }
#=> {false=>["nginx", "flip-flop"], true=>["help-me-1", "help-me-if-you-can"]}
puts "Error" if start_with_help_me[false].any? #=> Error

以防万一你需要获得更多信息,例如:

start_with_help_me[false].count #=> 3
start_with_help_me[true].count #=> 2

最新更新