2

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
Nodir Nasirov
  • 1,488
  • 3
  • 26
  • 44

7 Answers7

6
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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
4

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.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
3
fruits = ["Banana", "Apple", "Orange", "Grape"]
chars = 'ep'.chars

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

#=> ["Apple", "Grape"]
philip yoo
  • 2,462
  • 5
  • 22
  • 37
2
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)}}
sawa
  • 165,429
  • 45
  • 277
  • 381
2

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')}
Stangn99
  • 107
  • 1
  • 12
2

Here is one more way to do this:

fruits.select {|f| chars.downcase.chars.all? {|c| f.downcase.include?(c)} }
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
1

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"]