Reputation: 2832
I am still trying to figure out the difference between each and select after reading the documentation.
Can someone explain to me why each and select are replaceable in the below code? I don't understand why select is used and then the code-writer places it an array?? Also, what is a good way to understand their differences.
def word_unscrambler(str, words)
str_letters = str.split("").sort
anagrams = []
words.select do |word|
word_letters = word.split("").sort
anagrams << word if str_letters == word_letters
end
anagrams
end
Upvotes: 0
Views: 443
Reputation: 58284
Although it iterates the same way each
does, the purpose of select
is to return a collection based upon the select criteria. In that particular code snippet, it returns a collection based upon the truth value of anagrams << word if str_letters == word_letters
for each word
but then discards that collection.
Alternatively, it could have done it this way:
def word_unscrambler(str, words)
str_letters = str.split("").sort
words.select { |word| str_letters == word.split("").sort }
end
As was already said, the author of the code evidently doesn't understand how select
works.
Upvotes: 5
Reputation: 369536
I don't understand why
select
is used
Because the author of that code doesn't understand select
.
Upvotes: 4