Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 64 / 68

Checking Whether Two Words Are Anagrams

In this lesson you will learn to decide whether two words are anagrams - related by rearranging their letters. This is for anyone searching for "Ruby anagram check".

An anagram is a different word made from the same letters rearranged (for example, listen and silent). Sort the letters of both strings and see whether they match.

The sample code folds the case, splits into characters, and sorts with a.downcase.chars.sort and b.downcase.chars.sort before comparing. Notice the concise, idiomatic method chain, with .chars turning a string into an array of characters.

A common stumbling block for beginners is needing to unify the case with something like .downcase when the comparison should ignore it. Compare without normalising and words that really are anagrams get reported as different.

For long strings, counting how often each character occurs is faster. It is a basic technique for comparing strings while ignoring order, and it even applies to simple code-breaking games.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)