irhen irhen - 1 year ago 51
Ruby Question

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


Here's the situation. The 'arr' is an array converted from a string (and we get that string from user input). This code is checking if there's a zero in the 'arr', but it acts really weird. If the user inputs something like '123q', this message will be printed, even though there's no zero. Of course, if the input is '1230', it works just fine. I couldn't find any information about that, but i've spent a fairly good amount of time researching.

There's more to that.
Another piece of code, but closely related to my question.

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


In this case, if user input is '1230', this message will still be printed.

The question is: What's really going on there and how do i fix it? I need this code to check only for zero.

Ruby .include? method seems to think that 0 represents also all non-numerical characters and doesn't really represent itself. Is 0 non-numerical? How do i make it a number again so my 'if' would work the way i expect it to?

P.S. I'm using repl.it (current Ruby version 2.3.1p112) to run the code and there was no monkey-patching or anything like that.

Answer Source

use this:

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

Or

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

Update

"rew212340weq232".split('').map {|x| x[/\d+/]}.compact.map(&:to_i)
#=> [2, 1, 2, 3, 4, 0, 2, 3, 2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download