Quick search for a string or part of it in an Array

Asked

Viewed 231 times

4

I have the following array:

images = %W(
  droido 7midias vigilantes sebrae_mei dpe_saed websat ferpamweb dpe_chronus dpe_plantao
  promocast lolitaface dpe_intranet cha_bar clinica_sorriso droido_mascote bom_sabor
)

What I want is a way Ruby-Like to fetch a string as "cha_bar" or only part of string as "cha"

2 answers

3


I arrived at a very simple result using regular expression and index

images.index{|s| s =~ /cha_bar/}

or

images.index{|s| s =~ /cha/}

This will return to the position of String sought.

  • 1

    can use tbm images[x].include? 'cha'

  • Good too! I liked the regular expression for being smaller, but the tip is.

  • Humm, but include can be more interesting when working with variables...

  • yes, but in the end you can say that the structures are the same, the difference is that when you use {|s| s ...}, ruby already creates a foreach for your values

2

You can also use the method Enumerable#detect (or Enumerable#find) and it will return the first element that returns true in block condition:

images.find {|s| s =~ /lan/ } # => 'vigilantes'

Or, if you need all the elements that make the condition true, you can use Enumerable#select (or Enumerable#find_all):

images.select {|i| i =~ /lan/ } # => ["vigilantes", "dpe_plantao"]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.