# Flow of execution

Hi all,

Could someone explain the ‘flow’ of how the eg below is processed?
My limited understanding is that the left hand side is the receiver and
the right hand side the method being passed to the receiver?

What I don’t understand is where the block comes into the equation for
something like the following:

values = anagrams.values.sort do |a, b|
b.length <=> a.length
end

The block changes how the sort method sorts? ie it sorts by length
rather
than alphabetically? So it overrides the default meaning of <=>??

We get the values of the anagram hash by the ‘values’ method?
We then do:

.sort do |a, b| b.length <=> a.length end

ie this whole line acts on the values array??
not a 2 step process of 1. the sort method then 2. the block applied in
some way?

To illustrate what I’m failing dismally to explain here:
Using () for grouping, is it processed as A or B?

A
values = anagrams.values.(sort do |a, b| b.length <=> a.length)
end

B
values = anagrams.values.(sort) (do |a, b| b.length <=> a.length)
end

thanks,

Mark W. wrote:

b.length <=> a.length

ie this whole line acts on the values array??
not a 2 step process of 1. the sort method then 2. the block applied in
some way?

To illustrate what I’m failing dismally to explain here:
Using () for grouping, is it processed as A or B?

A
values = anagrams.values.(sort do |a, b| b.length <=> a.length)
end
This, almost. It’s more like:

values = anagrams.values.sort(do |a,b| b.length <=> a.length end)

The block essentially acts as a parameter to the sort method. The sort
method uses the result of passing each pair to the block to perform the
actual sorting.

Hi Alex,

On Mon, 29 Jan 2007 19:09:35 +0900, Alex Y. wrote:

values = anagrams.values.sort do |a, b|
.sort do |a, b| b.length <=> a.length end
end
This, almost. It’s more like:

values = anagrams.values.sort(do |a,b| b.length <=> a.length end)

The block essentially acts as a parameter to the sort method. The sort
method uses the result of passing each pair to the block to perform the
actual sorting.

excellent, thanks.