Hash and Array sorting - a bit confused

A

Alpha Blue

So, I have the following model method:

def self.cupcake_report_list
list = Schedule.find_all_by_division(2, :select =>
'schedules.team_id, schedules.cupcake', :eek:rder => :team_id)
cupcakes = []
list.each do |row|
teamname = ConferenceRecord.find_by_team_id(row.team_id, :joins
=> [:team, :conference])
cupcakes << {'name'=> teamname.team.name,
'teamid'=> teamname.team_id,
'cupcake' => row.cupcake,
'conference' => teamname.conference.short_name,
'confid' => teamname.conference_id}
end
return cupcakes
end

This returns and array of hashes:

120 rows: 0..119
Each row containing 5 hash key/values

Example:

test = cupcake_report_list

=> {"name"=>"Georgia Tech", "cupcake"=>"Jacksonville St.",
"conference"=>"ACC", "teamid"=>4, "confid"=>2}

What I want to do is sort the entire array by the name hash key so that
if I were to look within the array, it would like so:

test[0]
=> {"name"=>"Air Force", etc., etc., etc., etc.}
test[1]
=> {"name"=>"Akron", etc., etc., etc., etc.}
test[2]
=> {"name"=>"Alabama", etc., etc., etc., etc.}

etc..

I can't figure out a way to do that correctly by a specific hash key
within the array.

Any ideas on how I can accomplish this?

Many thanks.
 
7

7stud --

Alpha said:
Example:

test = cupcake_report_list

=> {"name"=>"Georgia Tech", "cupcake"=>"Jacksonville St.",
"conference"=>"ACC", "teamid"=>4, "confid"=>2}

What I want to do is sort the entire array by the name hash key so that
if I were to look within the array, it would like so:

test[0]
=> {"name"=>"Air Force", etc., etc., etc., etc.}
test[1]
=> {"name"=>"Akron", etc., etc., etc., etc.}
test[2]
=> {"name"=>"Alabama", etc., etc., etc., etc.}

etc..

I can't figure out a way to do that correctly by a specific hash key
within the array.

Any ideas on how I can accomplish this?

Many thanks.

test = [
{"name"=>"Zakron", "a" => "apple"},
{"name"=>"Akron", "a" => "goodbye"},
{"name"=>"Air Force", "a" => "hello"}
]

result = test.sort_by do |hash|
hash["name"]
end

p result

--output:--
[{"name"=>"Air Force", "a"=>"hello"}, {"name"=>"Akron", "a"=>"goodbye"},
{"name"=>"Zakron", "a"=>"apple"}]

result = test.sort_by do |hash|
hash["name"]
end

p result
 
A

Alpha Blue

Wow, why does it have to be so simple. :)

Thanks a ton. If you knew what I was trying to do to get this to work,
well, we'll pretend I didn't try all that stuff. :)

Thanks mate.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top