Ruby: 如何让数字再次变为零? .include?方法似乎很奇怪

Ruby: how to make zero a number again? The .include? method seems to act weird

  if arr.include?(0)
    puts "Please, try again. You cannot use zero!"
  end

情况是这样的。 'arr' 是一个从字符串转换而来的数组(我们从用户输入中获取该字符串)。这段代码正在检查 'arr' 中是否有零,但它的行为确实很奇怪。如果用户输入类似“123q”的内容,即使没有零,也会打印此消息。当然,如果输入是“1230”,它就可以正常工作。我找不到任何相关信息,但我花了相当多的时间进行研究。

还有更多。 又是一段代码,和我的问题密切相关

  if string.match(/\D/)
    puts "Please, try again. You cannot use non-numerical characters!"
  end

在这种情况下,如果用户输入“1230”,仍会打印此消息。

问题是:到底发生了什么,我该如何解决?我需要此代码来检查零。

Ruby.include?方法似乎认为 0 也代表所有非数字字符,并不真正代表自己。 0是非数字吗?我如何再次将其变成一个数字,以便我的 'if' 能够按照我期望的方式工作?

P.S。我正在使用 repl.it(当前 Ruby 版本 2.3.1p112)来 运行 代码并且没有猴子补丁或类似的东西。

使用这个:

if '123q'.chars.include?('0')
  puts "Please, try again. You cannot use zero!"
end

或者

if '1230'.chars.map(&:to_i).include?(0)
  puts "Please, try again. You cannot use zero!"
end

更新

"rew212340weq232".chars.map {|x| x[/\d+/]}.compact.map(&:to_i)
#=> [2, 1, 2, 3, 4, 0, 2, 3, 2]

不要将 string 转换为 integer,它总是导致 0

和0:

arr = "asds sad deff 0".chomp.split("")

 if (arr.include?(0) || arr.include?('0'))
    puts "Please, try again. You cannot use zero!"
  end

 result===>  Please, try again. You cannot use zero!

无 0:

arr2 = "asds sad deff".chomp.split("")

 if (arr2.include?(0) || arr2.include?('0'))
    puts "Please, try again. You cannot use zero!"
  end

 result===>  nil

您可以在数组中测试 '0' or 0 并打印语句

您的输入可能不是 '1230',而是 "1230\n",并且 /\D/ 匹配 "\n"

您可以使用 chomp 删除尾随的换行符,并编写一个正则表达式来检查是否只有数字而没有 0:

input.chomp =~ /\A[1-9]+\z/

正如其他人所说,问题是 String#to_i returns 0 对于非数字值。

解决这个问题的一个更简单的方法是根本不将用户输入拆分为数组,而只是使用正则表达式,就像您在第二个代码示例中所做的那样:

loop do
  puts(defined?(user_input) ? 'Please enter a value:' : 'No zeroes allowed! Please try again:')
  user_input = gets.chomp
  break unless user_input.match(/0/)
end

另外,http://rubular.com 是一个测试正则表达式的好站点。 '1234' 匹配 /\D/,所以您的实现可能有问题。