Ruby忽略了用户的字符串输入 - 将字符串转换为整数

时间:2014-12-11 22:43:10

标签: ruby calculator

print "How many miles are you driving? (number only) "
miles = gets.to_s.chomp

print "How expensive is gas per gallon? (just give a number) "
gas_price = gets.to_s.chomp

print "What type of car do you drive? "
car = gets.to_s.chomp.downcase


if car == "toyota"
  mpg = gets.to_s.chomp    
  mpg == 23
else 
  print "How many miles per gallon does your car get? "
  mpg = gets.to_s.chomp
  end


def gas_total(miles,gas_price,mpg)
  puts "Calculating the cost..."
  return (Integer(miles)/ Integer(mpg)) * Integer(gas_price)
  end

puts "It will cost you #{gas_total(miles,gas_price,mpg)} dollars"

这就是我的代码,一切都很有效,除非我问一个问题“你驾驶什么类型的汽车”。我可以回答“丰田”但我再次提示输入一个数字。

我希望当我输入“toyota”时,计算机会像我说mpg = 23那样处理它。

此外,还有一种比两次输入mpg = gets.to_s.chomp更有效的方法吗?

2 个答案:

答案 0 :(得分:0)

  

我希望当你输入“toyota”时,计算机会在你说mpg = 23时对其进行处理。

那么在那种情况下,你为什么要提示另一个号码呢?只需在mpg = 23块中指定if

答案 1 :(得分:0)

mpg = gets.to_s.chomp    
mpg == 23

这里出了点问题。你要求它给你一个值,然后进行评估,只要坐在那里就会返回真/假。

我认为你需要摆脱mpg = gets.chomp并将mpg == 23变成mpg = 23.