ruby - How to match given characters in string -
given:
fruits = %w[banana apple orange grape] chars = 'ep' how can print elements of fruits have characters of chars? tried following:
fruits.each{|fruit| puts fruit if !(fruit=~/["#{chars}"]/i).nil?)} but see 'orange' in result, not have 'p' character in it.
just fun, here's how might regular expression, magic of positive lookahead:
fruits = %w[banana apple orange grape] p fruits.grep(/(?=.*e)(?=.*p)/i) # => ["apple", "grape"] this nice , succinct, regex bit occult, , gets worse if want generalize it:
def match_chars(arr, chars) expr_parts = chars.chars.map {|c| "(?=.*#{regexp.escape(c)})" } arr.grep(regexp.new(expr_parts.join, true)) end p match_chars(fruits, "ar") # => ["orange", "grape"] also, i'm pretty sure outperformed or of other answers.
Comments
Post a Comment