N N
N N

Reputation: 1638

How to match given characters in string

Given:

fruits = %w[Banana Apple Orange Grape]
chars = 'ep'

how can I print all elements of fruits that have all characters of chars? I tried the following:

fruits.each{|fruit| puts fruit if !(fruit=~/["#{chars}"]/i).nil?)}

but I see 'Orange' in the result, which does not have the 'p' character in it.

Upvotes: 2

Views: 195

Answers (7)

Andrea Cadamuro
Andrea Cadamuro

Reputation: 11

Try this, first split all characters into an Array ( chars.split("") ) and after check if all are present into word.

fruits.select{|fruit| chars.split("").all? {|char| fruit.include?(char)}}
#=> ["Apple", "Grape"]

Upvotes: 1

Wand Maker
Wand Maker

Reputation: 18762

Here is one more way to do this:

fruits.select {|f| chars.downcase.chars.all? {|c| f.downcase.include?(c)} }

Upvotes: 2

Jordan Running
Jordan Running

Reputation: 106027

Just for fun, here's how you might do this with a regular expression, thanks to the magic of positive lookahead:

fruits = %w[Banana Apple Orange Grape]
p fruits.grep(/(?=.*e)(?=.*p)/i)
# => ["Apple", "Grape"]

This is nice and succinct, but the regex is a bit occult, and it gets worse if you want to 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 this would be outperformed by most or all of the other answers.

Upvotes: 4

philip yoo
philip yoo

Reputation: 2512

fruits = ["Banana", "Apple", "Orange", "Grape"]
chars = 'ep'.chars

fruits.select { |fruit| (fruit.split('') & chars).length == chars.length }

#=> ["Apple", "Grape"]

Upvotes: 3

Stangn99
Stangn99

Reputation: 117

I'm an absolute beginner, but here's what worked for me

fruits = %w[Banana Apple Orange Grape] 
chars = 'ep'

fruits.each {|fruit| puts fruit if fruit.include?('e') && fruit.include?('p')}

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110675

p fruits.select { |fruit| chars.delete(fruit.downcase).empty? }
["Apple", "Grape"]

String#delete returns a copy of chars with all characters in delete's argument deleted.

Upvotes: 6

sawa
sawa

Reputation: 168101

chars.each_char.with_object(fruits.dup){|e, a| a.select!{|s| s.include?(e)}}
# => ["Apple", "Grape"]

To print:

puts chars.each_char.with_object(fruits.dup){|e, a| a.select!{|s| s.include?(e)}}

Upvotes: 2

Related Questions