Ruby中的动态变量名称

时间:2014-04-25 06:25:11

标签: ruby variables dynamic

@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

有没有比调用set方法中的get方法更好的方法呢?我真的只是想+=动态变量......

3 个答案:

答案 0 :(得分:1)

另一个解决方案,没有循环(假设关系是运动has_many游戏)

@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
}

答案 1 :(得分:1)

根据@Santosh的回答,你可以更普遍地做到这一点:

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

答案 2 :(得分:0)

@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