简体   繁体   中英

Array of Images Ruby to check what each value starts with

I have an array of different images. I am trying to confirm that if the images start with the right name.

images = ["nginx", "help-me-1"]

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

Unfortunately its not looping through correctly, and I'm unsure whats wrong. I don't get an error message of any sort, and I've added some logging expecting some and do not. What might I be missing?

Perhaps this is what you want?

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

Or do you want to raise or puts ?

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

Basically if its not true for all, print an error message. If it is true, continue on.

I guess the best option is in the comment above from @Sergio Tulentsev .

Anyhow, this is just a further idea:

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

Just in case you would need to get more info, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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