Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Searching String Arrays

Is there a way to search through a large array of string for a specific entry, using only a part of the total string? (and then return the string's number in the array). Basically, I want a large array of strings, like say, card names. And then, I want to be able to search something like "Cyber", and return the locations of the strings in the array that contain "Cyber", e.g. "Cyber Dragon, "Cyber Harpie Lady", etc. Any help would be appreciated.
 

khmp

Sponsor

Code:
def search_array(array, word)
  results = []
  array.each_index do |i|
    results << i if array[i].downcase.include?(word.downcase)
  end
  return results
end

This accomplishes the same as Array.index but this gets every matching element and traverses the array of strings entirely. It doesn't stop on the first one it finds. If you want to get the index of the first occurrence it encounters:

Code:
def search_array(array, word)
  array.each_index do |i|
    return i if array[i].downcase.include?(word.downcase)
  end
  return nil
end

If you want the search to be case sensitive remove the ".downcase".

Good luck with it Glitchfinder! :thumb:
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top