Ruby for are these chars in this string…

I find myself wanting to know if the characters in one string are in another.
For example, if you have a key space for a string key name, making sure the provided key is valid.


require 'set'
def chars_subset_of? checkme, inme
checkme.split(//).to_set.subset? inme.split(//).to_set
end

You could also toss this inside class String to dynamically add the method


require 'set'
def chars_subset_of? other_string
if other_string.class == String
self.split(//).to_set.subset? other_string.split(//).to_set
else # just try
self.split(//).to_set.subset? other_string.to_set
end
end

Leave a Reply