Forgive me if my code is off. I've still got my head in Ruby on Rails which seems to have subtle differences that are coming out as I learn more "just Ruby," although to be fair I'm not sure my code would pass muster in a Ruby on Rails format. I digress.
I am trying to compare two arrays that contain a set of strings. I want to do a couple things. 1) Ensure that the arrays are the same number of words, otherwise the exercise is moot. 2) Compare the first word in an array with only the first word in the second array. In other words, I never want to compare word 1 in array "a" with word 4 in array "b". I'm struggling to find a solution that reorders the characters in any given word, compares it to the reordered characters in the corresponding word in the second array, and prints 1 if it's an anagram (once sorted, the idea is that the two words would be equivalent) or 0 if they do not match.
In the example below, what I want it to print is:
0
0
1
1
...but that is not happening. Thoughts? I'm afraid this has to do with local variable issues, but I am not be sure.
a = ['hello', 'goodbye', 'pants', 'baa']
b = ['helio', 'godbye', 'spant', 'aba']
x = a.length
y = b.length
z = 0
x = y? do
while z < x do
if a.find(z).chars.sort.join == b.find(z).chars.sort.join
puts 1
else
puts 0
end
z += 1
end
end
[Edit: I've edited my answer to incorporate an efficiency improvement suggested by @raph in a comment on the question (the method
anagram?
below). That may not be necessary, but I thought it was such a good idea that it should get some exposure. I've also given a detailed explanation, as the OP is new to Ruby, as might be other readers.]You might consider doing it as follows.
Code
Example
Explanation
anagrams
methodFor the example above,
so we don't return
nil
in the first line ofanagrams
.Next,
Assuming for a moment that
anagram?
works as desired:Enumerable#map passes each element of
c
(a two-element array) into the block.1. It is clearer, however, to decompose (or "disambiguate") those arrays and assign each of the two words they comprise to a block variable2:The first element passed in is
["hello", "helio"]
, soand we execute
which is shorthand for
anagram?
methodSo now let's move on to
anagram?
, withSince
we don't return.
Count frequency of letters in the first word
Let me now write the next few lines of
anagram?
slightly differently:(The last line is there just to show the value of the hash.)
In the first line we create a hash
counts
with a default value of zero. All this means is that ifcounts
does not contain the keyk
,counts[k]
will return the default value. Very important: doing so does not change the hash!3String#each_char4 passes each character of
"hello"
into the block and assigns it to the block variablec
. Initially,c='h'
andh={}
. We then executewhich is shorthand for
Since
counts
does not yet have a key'h'
,counts['h']
on the right returns the default value:Similarly, after
'e'
and the first'l'
are passed to the block, we have:However, when we pass the second
'l'
, we executeand we finish up with
The method Enumerable#each_with_object will become a good friend
This method is used merely to save some steps. It allows us to write:
as
and we can also get rid of the line
by writing
This may seem like a small saving, but there are many other situations where the use of
each_with_object
and otherEnumerable
class methods permit the chaining of methods, which is extremely useful.Decrementing letter counts for letters in the second word
Recall
We now execute
First,
'h'
is passed into the block. Ascounts['h'] #=> 1
, we executecounts['h'] -= 1
, so nowAfter passing
'e'
and'l'
to the block,but when we pass
'i'
, we find(i.e., the default value of zero is returned, and we don't want to set
counts['i']
to-1
) so we returnfalse
, having concluded that the two words are not anagrams. (Had the second word been"heeio"
, we would have returnedfalse
when the second'e'
was passed to the block.)Do we have an anagram?
Since two two words have the same length, if we are able to process all characters of the second word without returning
false
, we must end up with(no need to check!), meaning the two words are anagrams, so in this case we would return
true
toanagrams
.5 Hence, the last line ofanagram?
.Notes
1 Under the hood, this is what's happening:
Here we can see what elements the enumerator will pass into the block, but sometimes you need to convert the enumerator to an array to get that information:
It is actually the method Array#each that passes the elements of
enum
into the block:2 If we pass
[[1,2],3]
into a block, and the block variables are written|(a,b),c|
, thena=>1
,b=>2
,c=>3
. This is quite handy. Cool, eh?.3
Note there is a form of Hash#new that takes block, which allows keys not in the hash to be added when they are referenced.
4 Instead of
aw_down.each_char
we could have writtenaw_down.chars.each
, butaw_down.chars
creates an unnecessary intermediate array.each_char
, an enumerator, merely passes values as they are required.5 We could return
0
rather thanfalse
and1
rather thantrue
, in which case we could writein
anagrams
, but wouldn't it be clearer to haveanagrams
return an array whose values aretrue
orfalse
, rather than0
or1
?