Dudo
Dudo

Reputation: 4169

Dynamic variable names in Ruby

@baseball_games = 0
@basketball_games = 0
@football_games = 0

Game.all.each do |game|
  instance_variable_set("@#{game.sport.name.downcase}_games", instance_variable_get("@#{game.sport.name.downcase}_games") + 1)
end

Is there a better way to do this, than calling the get method inside the set method? I really am just trying to += the dynamic variable...

Upvotes: 0

Views: 142

Answers (3)

Uri Agassi
Uri Agassi

Reputation: 37409

Building upon @Santosh's answer, you could do this more generally:

@games = Sport.all.map { |sport| [sport.name.to_sym, sport.games.count] }.to_h

Upvotes: 1

Santhosh
Santhosh

Reputation: 29094

Another solution, without the loop (Assuming the relation is sport has_many games)

@games = {
  :baseball => Sport.find_by_name('baseball').games.count,
  :basketball => Sport.find_by_name('basketball').games.count,
  :football => Sport.find_by_name('football').games.count
}

Upvotes: 1

SreekanthGS
SreekanthGS

Reputation: 988

@games = {:baseball => 0, :basketball => 0, :football => 0 }
Game.all.each do |game|
  @games[game.sport.name.downcase.to_sym] = @games[game.sport.name.downcase.to_sym] + 1
end

Upvotes: 0

Related Questions