Stefano Crocco wrote:
> Alle Wednesday 30 January 2008, Adam Akhtar ha scritto:
>> > included in the hash, the [] method returns 0). Then, there's an
>> > iteration on
>> > all items of the array. For each element, the value of the hash item
>> > corresponding to the array element is increased by one.
>>
>> If the hash is empty to begin with, when you try to look up the key
>> using res[i]
>> wont it just return 0. I cant see where the hash res is assigned with
>> the unique values from a.
>
> writing
>
> var += something
>
> is the same as writing
>
> var = var + something
>
> In fact, ruby actually translate the first form into the second. So,
> when I
> write
>
> res[i] += 1
>
> I mean:
>
> res[i] = res[i] + 1
>
> When the hash is emtpy (or it doesn't contain i), the call to res[i] on
> the
> right hand gives 0, so that res[i] + 1 becomes 1. Then you have the
> assignment:
>
> res[i] = 1
>
thanks for the info on adding to hashes. I think i understand the res[i]
= res[i] + 1 bit. If we have an array such as [a, b, b, c, c, c] and
turn it into a hash like this
a -> 1
b -> 2
c -> 3
using your code above when i iterate through the array i do something
like this
res[a] = res[nil] + 1
res[a] = 0 + 1
res[a] = 1 #( a -> 1 ) right???
next iteration
res[b] = res[b] + 1
res[b] = 0 + 1 #( b -> 1 ) right??
next iteration
res[b] = res[b] + 1
res[b] = 1 + 1
res[b] = 2 #ta da!!!!
and so on
is that how its working?
Got to say thats pretty slick!
--
Posted via
http://www.ruby-forum.com/.