user1658296
user1658296

Reputation: 1418

ruby quick string subset analysis

I have two strings:

"0123"
"023"

I want to be able to show that '0', '2' and '3' exist in "0123", I have tried arrays, sets, and substring methods on the string, with no avail.

Is there some way to do this efficiently?

Upvotes: 1

Views: 247

Answers (4)

peter
peter

Reputation: 42192

This returns whether all chars of one string are present in the second, by iterating over each byte-value of the needed string and checking if the character-value is present in the string to check, joining the result to a string and comparing this with the needed string to return true or false.

to_check = '0123'
to_check2 = '9123'
needed = '023'

p needed.each_byte.map{|c|to_check[c.chr]}.join == needed #true
p needed.each_byte.map{|c|to_check2[c.chr]}.join == needed #false

Upvotes: 0

KARASZI István
KARASZI István

Reputation: 31467

You can use Array intersection (Array#&):

a = '0123'.chars
b = '023'.chars

intersections = a & b

Upvotes: 3

Henrik Andersson
Henrik Andersson

Reputation: 47182

I'm thinking about the two strings as arrays and then as sets and then trying to get the difference between them. But you don't want the difference you want the similarities, so that's why the ! is before the include.

a.split("").reject{|x| !"023".split("").include?(x)}

This could then further be refined to be a bit more readable

first_string = "0123".split("")
second_string = "023".split("")

first_string.reject{ |x| !second_string.include?(x) }

and lastly if you want something more Ruby-esque you could use intersections.

result = first_string & second_string

Upvotes: 1

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

This works perfectly.

matches = []
"023".each_char { |c| matches << c if "0123".index(c) }

p matches # Output ["0", "2", "3"]

Upvotes: -1

Related Questions