Ruby For Rails Question

I am confused about the following method on page 415. Where did the b
come from? What is the end.reverse?

def rank(list)
list.uniq.sort_by do |a|
list.select {|b| a == b }.size
end.reverse
end

Hi –

On Wed, 11 Oct 2006, Bala P. wrote:

I am confused about the following method on page 415. Where did the b come from? What is the end.reverse?

def rank(list)
list.uniq.sort_by do |a|
list.select {|b| a == b }.size
end.reverse
end

b is the block param for the second block (the one that goes with
select). The reverse reverses the results up to that point.

Basically it’s a chain of array transformations.

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

At 1:11 PM -0700 10/11/06, Bala P. wrote:

I am confused about the following method on page 415.
Where did the b come from? What is the end.reverse?

def rank(list)
list.uniq.sort_by do |a|
list.select {|b| a == b }.size
end.reverse
end

The do block that begins “list.uniq …” extracts unique
values from list, then sorts them by the expression:

list.select {|b| a == b }.size

This expression extracts sublists of list, where each item
(b) matches the current value of a. The “size” method then
tallies the number of elements in each sublist. In short,
we are sorting by the number of times that each unique item
appears in the initial list.

This gives us a list of instruments which is sorted by the
number of compositions in which it appears. “reverse” then
reverses the order of the sorted list. (I think :slight_smile:

-r

P.S. This is really more of a Ruby question than a Rails one;
you might want to post such to [email protected]

http://www.cfcl.com/rdm Rich M.
http://www.cfcl.com/rdm/resume [email protected]
http://www.cfcl.com/rdm/weblog +1 650-873-7841

Technical editing and writing, programming, and web development

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs