Kopty
Kopty

Reputation: 548

Ruby - iterating through database results and storing them in a hash

Consider the following:

details = Hash.new

# Example of this Hash's final look
details["team1"] = "Example"
details["team2"] = "Another team"
details["foo"]   = "Bar"

The way I get the names of the two teams is through:

teams = Match.find(1).teams
=> [#<Team id: 1, name: "England">, #<Team id: 2, name: "Australia">]

Now I would like to save the names of the teams into the Hash under team1 and team2. If I were using arrays I could do:

teams.each do |team|
  details << team.name
end

However, I need to do this with the Hash I have shown above. How would one go about accomplishing this?

Upvotes: 1

Views: 390

Answers (4)

Santanu Karmakar
Santanu Karmakar

Reputation: 336

{}.tap do |h|
  Match.find(1).teams.each_with_index {|t, i| h["team#{i+1}"] = t.name}
end

Upvotes: 0

evfwcqcg
evfwcqcg

Reputation: 16335

Hash[teams.map { |x| ["team_#{x.id}", x.name] }]
# => {"team_1"=>"England", "team_2"=>"Australia"}

If you want to keep id 1 and 2

Hash[a.map.with_index { |x,i| ["team_#{i.succ}", x.name] }]
# => {"team_1"=>"England", "team_2"=>"Australia"}

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

What about this?

teams.each_with_index do |team, idx|
  id = "team#{idx + 1}"
  details[id] = team.name
end

Here you take the team object and make hash key out of it, and then use that key to set a value.

Upvotes: 2

Kulbir Saini
Kulbir Saini

Reputation: 3915

How about using an inject for a one liner?

teams.inject({}){ |details, team| details["team#{team.id}"] = team.name; details }

The return value will be an Array or Hashes.

Upvotes: 1

Related Questions