Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a pattern in an array

Tags:

arrays

ruby

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?

like image 960
TheOneTeam Avatar asked Apr 30 '12 09:04

TheOneTeam


People also ask

How do you find the pattern of an array?

You find a pattern by checking if the sequence starting at every plen element match the first plen elements of the array. So if the current plen is 3 , then you check if elements at index 3 to 5 (inclusive) matches the elements at index 0 to 2 (inclusive). If they match you check the next sequence starting at index 6 .

What is pattern matching in OCaml?

Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.

Why ++ is not allowed in pattern matching?

You can only pattern-match on data constructors, and ++ is a function, not a data constructor. Data constructors are persistent; a value like 'c':[] cannot be simplified further, because it is a fundamental value of type [Char] .


2 Answers

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 
like image 197
ghoppe Avatar answered Sep 19 '22 14:09

ghoppe


Well you can grep (regex) like this:

test.grep /boy/ 

or even better

test.grep(/boy/).any? 
like image 33
Roger Avatar answered Sep 21 '22 14:09

Roger