is a microblog
home archives search feed blogroll

Check If A String Contains Any Character Of Another String

Looks like there’s no function to do this out of the box in Ruby.

def contains_any(word, chars)
  (word.split('') & chars.split('')).any?

p (contains_any('Hello', '*\-o') ? 'yes' : 'no')

split('') turns the string into an array of character. x & y checks if any element of y is included in x. The code above would output yes because the string Hello contains the character o.

Or you could use a regular expression.

Posted on 2018-03-05   #ruby  

← Next post    ·    Previous post →