【问题标题】:I'm trying to convert a value to an integer what am I doing wrong here?我正在尝试将值转换为整数我在这里做错了什么?
【发布时间】:2019-06-07 03:12:58
【问题描述】:

我只是想让这段代码正常工作,而且我不断得到:

请告诉我我做错了什么。

我正在学习,我已经完成了我能想到的代码的每一次迭代,试图让它工作,我只是不确定我做错了什么。

puts "How old are you?"
old = gets.chomp

if old <= 21
  return "You are not legally allowed to buy alcohol in the US"
else 
  return "You are legally allowed to buy alcohol in the US"
end

【问题讨论】:

  • 如果old.to_i &lt;= 21gets.chomp.to_iget.to_i 相同。
  • “我正在尝试将一个值转换为整数” – 您似乎意识到您必须将输入值转换为整数。但是您的代码中不会发生转换。您正在将未转换的输入与整数 21 进行比较,而 Ruby 告诉您它无法以这种方式将字符串与 21 进行比较。

标签: ruby syntax


【解决方案1】:

我相信你必须使用to_i将字符串转换为整数。

【讨论】:

    【解决方案2】:

    前面的答案是正确的,但更冗长,这是您需要在代码中更改的行:

    old = gets.chomp.to_i
    

    但您可能还想确保用户只输入一个整数,因为在非数字字符上调用 .to_i 将返回 0

    你可能想看看Accept only numeric input

    【讨论】:

    • 不需要chomp
    • “这是您需要更改的行 [...] 您可能还想确保用户只输入一个整数” – 挑剔,但如果你把 @987654326 @ 就在那里,你不能再检查非整数了。
    【解决方案3】:

    根据需要尝试/改进:

    input = gets.chomp
    
    if(val = Integer(input) rescue false)
      val < 21 ? 'Not old enough' : 'The usual martini?'
    else
      'You did not provide an age (number)'
    end
    

    它会检查输入是否为整数,因此它会考虑像foo 这样的输入。

    第...

    【讨论】:

    • 您可以在最近的 Ruby 版本中使用 Integer(input, exception: false)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2013-06-28
    • 2023-01-19
    相关资源
    最近更新 更多