Suppose I have an arbitrary list of strings and some lists of keywords.
~list_of_strings = ["cat", "dog", "fish", "yellow", "blue", "furry"];
~keywordsA = ["cat", "yellow", "furry"];
~keywordsB = ["cat", "green", "furry"];
I need some sort of filter function to know whether or not the list of arbitrary strings contains all the keywords. Something like this:
~list_of_strings.filter_function( ~keywordsA ) --> True
~list_of_strings.filter_function( ~keywordsB ) --> False
Is there a language function that already allows me to do this kind of check?
Thank you so much for your support
jordan
November 1, 2022, 11:36am
2
Collection.includesAll(aCollection)
? Would that method work, something like :
list_of_string.includesAll(keywordA)
Or you could build your own with every…
key.every{
|k|
list.includes(k)
}
1 Like
Thanks @jordan for your reply,
despite the method works for integer collections, it seems not to work for strings collection.
I mean, when I evaluate these lines of code:
~list_of_strings.includesAll( ~keywordsA );
~list_of_strings.includesAll( ~keywordsB );
They both are returning False
. Why?
It works with symbols:
~list_of_strings = [\cat, \dog, \fish, \yellow, \blue, \furry];
~keywordsA = [\cat, \yellow, \furry];
~list_of_strings.includesAny(~keywordsA) // → true
1 Like
rdd
November 1, 2022, 8:55pm
5
They both are returning False. Why?
includesAll sends includes which sends ===, and strings aren’t ===, they’re only ==.
includesAllEqual is:
+ Collection {
includesAllEqual { | aCollection |
aCollection.do { | item | if (this.includesEqual(item).not) {^false} };
^true
}
}
2 Likes
jordan
November 1, 2022, 11:02pm
6
As a general rule of thumb you should only use strings when you are manipulating them, but once the string is fixed it should be converted to a symbol. String comparison is slow whilst symbol comparison is significantly faster as symbols are stored in a hash map, so you just compare the hashes rather than every letter like in a string.
2 Likes
Thank you guys for your help.
Below code works for me:
~list_of_strings = ["cat", "dog", "fish", "yellow", "blue", "furry"];
~keywordsA = ["cat", "yellow", "furry"];
~keywordsB = ["cat", "green", "furry"];
~list_of_strings.collect({|e| e.asSymbol}).includesAll( ~keywordsA.collect({|e| e.asSymbol}) ); ---> true
~list_of_strings.collect({|e| e.asSymbol}).includesAll( ~keywordsB.collect({|e| e.asSymbol}) ); ---> false