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
  • 160,959
  • 41
  • 265
  • 366
Nodir Nasirov
  • 1,273
  • 1
  • 20
  • 38

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
  • 101,330
  • 6
  • 60
  • 95
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
  • 97,653
  • 15
  • 175
  • 173
3
fruits = ["Banana", "Apple", "Orange", "Grape"]
chars = 'ep'.chars

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

#=> ["Apple", "Grape"]
philip yoo
  • 2,362
  • 4
  • 21
  • 34
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
  • 160,959
  • 41
  • 265
  • 366
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
  • 97
  • 1
  • 11
2

Here is one more way to do this:

fruits.select {|f| chars.downcase.chars.all? {|c| f.downcase.include?(c)} }
Wand Maker
  • 18,008
  • 8
  • 50
  • 83
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"]