Iggy Iggy - 1 month ago 5x
Ruby Question

Check whether a string contains all the characters of another string in Ruby

Let's say I have a string, like

string= "aasmflathesorcerersnstonedksaottersapldrrysaahf"
. If you haven't noticed, you can find the phrase
"harry potter and the sorcerers stone"
in there (minus the space).

I need to check whether
contains all the elements of the string.

string.include? ("sorcerer") #=> true
string.include? ("harrypotterandtheasorcerersstone") #=> false, even though it contains all the letters to spell harrypotterandthesorcerersstone

Include does not work on shuffled string.

How can I check if a string contains all the elements of another string?


Sets and array intersection don't account for repeated chars, but a histogram / frequency counter does:

require 'facets'

s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
s2.chars.frequency.all? { |char, count| freq1[char] >= count } 
#=> true

No need to use facets if you don't want to add the dependency, of course, writing your own Array#frequency is pretty straightforward.

class Array
  def frequency
    Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }