32

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
  • 35,848
  • 27
  • 79
  • 88
TheOneTeam
  • 24,336
  • 44
  • 110
  • 154

6 Answers6

52

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
  • 20,640
  • 3
  • 28
  • 20
  • 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,095
  • 20
  • 20
Roger
  • 7,357
  • 5
  • 38
  • 61
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,633
  • 3
  • 28
  • 54
Richard Luck
  • 641
  • 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
  • 416
  • 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,178
  • 5
  • 60
  • 104
  • 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,095
  • 20
  • 20