初学者。有一个自定义类方法,可以计算team_a和team_b相互比赛的获胜概率。在我看来,我想显示那些计算。试着将这个与我对其运作方式的有限理解结合在一起。
# team.rb
class Team
attr_reader :home_team_win_probability, :away_team_win_probability
def self.matchup(home_team, away_team)
home_team_win_probability = (home_team.rating - home_team.rating * away_team.rating) / (home_team.rating) + away_team.rating - 2 * home_team.rating * away_team.rating)
away_team_win_probability = 1 - home_team_win_probability
end
end
# teams_controller.rb
class TeamsController < ApplicationController
def matchups
@team_a = Team.find_by(rank: 2)
@team_b = Team.find_by(rank: 1)
@matchup = Team.matchup(@team_a, @team_b)
end
end
# matchups.html.erb
<h4>Matchup: <%= @team_a.name %> @ <%= @team_a.name %></h4>
# want to do something like this:
<h5>Home Team Win Probability: <%= @matchup.home_team_win_probability %> </h5>
<h5>Away Team Win Probability: <%= @matchup.away_team_win_probability %> </h5>
@matchup.home_team_win_probability
产生错误,因为@matchup只返回最后一行(在这种情况下是客队概率)@matchup.home_team_win_probability => undefined method home_team_win_probability for #<BigDecimal:0x007f860872b3f8
如何在我的自定义类方法中调用home_team_win_probability
和away_team_win_probability
?感谢。
答案 0 :(得分:1)
改为返回哈希:
def self.matchup(home_team, away_team)
home_team_win_probability = (home_team.rating - home_team.rating * away_team.rating) / (home_team.rating) + away_team.rating - 2 * home_team.rating * away_team.rating)
away_team_win_probability = 1 - home_team_win_probability
{home: home_team_win_probability, away: away_team_win_probability}
end
然后访问:
@matchup[:home]
@matchup[:away]
答案 1 :(得分:1)
匹配逻辑需要在Team模型中没有特殊原因。我会创建一个新模型......
class Matchup
attr_accessor :home_team, :away_team
def initialize(home_team, away_team)
@home_team = home_team
@away_team = away_team
end
def home_team_win_probability
(home_team.rating - home_team.rating * away_team.rating) / (home_team.rating) + away_team.rating - 2 * home_team.rating * away_team.rating)
end
def away_team_win_probability
1 - home_team_win_probability
end
end
现在,您可以在TeamsController
...
@matchup = Matchup.new(@team_a, @team_b)
这为您提供了方法@matchup.home_team_probability
和@matchup.away_team_probability