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

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 Ruby-Like way to fetch a string as "cha_bar" or just part of string as "cha "

    
asked by anonymous 24.06.2016 / 20:21

2 answers

3

I came up with a very simple result using regular expression and index

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

or

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

This will return the position of String sought.

    
24.06.2016 / 20:28
2

You can also use the 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"]
    
26.06.2016 / 04:46