33

There is an array with 2 elements

test = ["i am a boy", "i am a girl"]

I want to test if a string is found inside the array elements, say:

test.include("boy")  ==> true
test.include("frog") ==> false

Can i do it like that?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

6 Answers6

54

Using Regex.

test = ["i am a boy" , "i am a girl"]

test.find { |e| /boy/ =~ e }   #=> "i am a boy"
test.find { |e| /frog/ =~ e }  #=> nil
ghoppe
  • 21,452
  • 3
  • 30
  • 21
  • 3
    @izomorphius True, but the poster did not specify if the string had to be a separate word or not. Simple to fix with a different Regex. – ghoppe Apr 30 '12 at 09:19
  • in fact I had some troubles creating the other regex. How do you say end of string or \w? – Ivaylo Strandjev Apr 30 '12 at 09:20
46

Well you can grep (regex) like this:

test.grep /boy/

or even better

test.grep(/boy/).any?
Flexoid
  • 4,155
  • 21
  • 20
Roger
  • 7,535
  • 5
  • 41
  • 63
6

Also you can do

test = ["i am a boy" , "i am a girl"]
msg = 'boy'
test.select{|x| x.match(msg) }.length > 0
=> true
msg = 'frog'
test.select{|x| x.match(msg) }.length > 0
=> false
Nithin
  • 3,679
  • 3
  • 30
  • 55
Richard Luck
  • 640
  • 7
  • 15
3

I took Peters snippet and modified it a bit to match on the string instead of the array value

ary = ["Home:Products:Glass", "Home:Products:Crystal"]
string = "Home:Products:Glass:Glasswear:Drinking Glasses"

USE:

ary.partial_include? string

The first item in the array will return true, it does not need to match the entire string.

class Array
  def partial_include? search
    self.each do |e|
      return true if search.include?(e.to_s)
    end
    return false
  end
end
Brett
  • 446
  • 5
  • 4
2

If you don't mind to monkeypatch the the Array class you could do it like this

test = ["i am a boy" , "i am a girl"]

class Array
  def partial_include? search
    self.each do |e|
      return true if e[search]
    end
    return false
  end
end

p test.include?("boy") #==>false
p test.include?("frog") #==>false

p test.partial_include?("boy") #==>true
p test.partial_include?("frog") #==>false
peter
  • 41,770
  • 5
  • 64
  • 108
  • I would not necessarily say that this is the "best" way per se considering that class modifications are available in every other ruby code / project too. It definitely is one way though. – shevy Apr 30 '17 at 09:47
1

If you want to test if a word included into the array elements, you can use method like this:

def included? array, word
  array.inject([]) { |sum, e| sum + e.split }.include? word
end
Flexoid
  • 4,155
  • 21
  • 20