2015-06-23 87 views
0

我目前使用這個代碼,以使總統預測:使用變量輸入

require 'csv' 
require 'statistics2' 
require 'pollster' 
require 'uri' 
include Pollster 

poll = Poll.where(:chart => '2016-national-gop-primary').first 
responses = poll.questions.detect { |question| question.chart == '2016-national-gop-primary' }.responses 
rubio = responses.detect { |response| response[:choice] == "Rubio" } 
bush = responses.detect { |response| response[:choice] == "Bush" } 
walker = responses.detect { |response| response[:choice] == "Walker" } 
carson = responses.detect { |response| response[:choice] == "Carson" } 
huckabee = responses.detect { |response| response[:choice] == "Huckabee" } 
paul = responses.detect { |response| response[:choice] == "Paul" } 
cruz = responses.detect { |response| response[:choice] == "Cruz" } 

difference = rubio[:value] - walker[:value] 
negativechance = Statistics2.tdist(2,(difference/3)) 
nchance = 1 - (Statistics2.tdist(2,(difference/3))) 

if difference < 0 
then puts "#{nchance.to_f*100}""%" + " Walker." 
    puts "#{(1-nchance.to_f)*100}""%" + " Rubio." 
    puts "Based on latest poll at Pollster.com" 
else puts "#{negativechance.to_f*100}}""%" "Rubio." 
    puts "#{(1-negativechance.to_f)*100}""%" + " Walker." 
    puts "Based on latest poll at Pollster.com" 
end 

我希望用戶能夠輸入最後兩個名字找到誰就能贏得投影。如果我改變這個:

difference = rubio[:value] - walker[:value] 

變量它告訴我我沒有價值。

在此先感謝。

+0

什麼反應的樣子? (me == #ruby baweaver) – baweaver

+0

迴應 - https://gist.github.com/AthleteInvictus/57e337e222b4bde87235 – baweaver

回答

0

這看起來非常像KV對(哈希),所以如果您選擇關鍵和價值的價值?使用這個鍵你可以很容易地獲得動態選擇,但是你必須自己做一些動作。

你需要從這個去:

[{a: 'foo', b: 1}, {a: 'bar', b: 21}, {a: 'baz', b: 13}] 

要這樣:

{'foo' => 1, 'bar' => 21, 'baz' => 13} 

提示:你會需要地圖和to_h

[[:a, 1]].to_h # => {a: 1}