使用变量输入

时间:2015-06-23 20:54:12

标签: ruby variables

我目前正在使用此代码进行总统预测:

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]

变量它告诉我我没有价值。

提前致谢。

1 个答案:

答案 0 :(得分:0)

看起来很像KV对(哈希),所以如果你选择键并重视价值怎么办?使用该密钥,您可以非常轻松地获得动态选择,但是您将不得不自己做一些腿部工作。

你需要离开:

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

对此:

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

提示:你需要map和to_h

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