Ruby Key Using Split and Join -
i have written exam here, here's instruction.
write program prints out groups of words anagrams. anagrams words have same exact letters in them in different order. output should this:
["demo", "dome", "mode"] ["neon", "none"]
(etc)
and here's solution this:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] result = {} words.each |word| key = word.split('').sort.join if result.has_key?(key) result[key].push(word) else result[key] = [word] end end result.each |k, v| puts "------" p v end
i've been trying understand ruby code solution can't grasp it. 1 of question how can test result
hash if has no key or element contain it. thing how .join
, .sort
works on code.
i confuse how go thru answer. can out there can explain on codes line line in layman's term beginner dummy me can understand?
i this:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] words.group_by { |word| word.chars.sort }.values #=> [["demo","dome","mode"],["none","neon"],["tied","diet","edit","tide"],["evil","live","veil","vile"],["fowl","wolf","flow"]]
Comments
Post a Comment