Arrays in Ruby, how to deal with this situation?

Let's say I have the following array:

arr = ["", "2121", "8", "myString"]


I want to return false if the array contains any non-digit characters.


source to share

2 answers

If blank lines are allowed:

def contains_non_digit(array)
    ! {|s| s =~ /^.*[^0-9].*$/}.empty?


Explanation: This filters the array for all strings that match the regex. This regular expression evaluates to true for a string containing at least one non-digit character. If the resulting array is empty, the array does not contain strings without numbers. Finally, we need to deny the result, because we want to know that the array contains non-digit strings.



arr.all? { |s| s =~ /^\d+$/ }


This will check each item if it is only digits ( \d

). If any of them are missing, false is returned.

Edit: You haven't fully specified whether the empty string is valid or not. If so, the line should be rewritten as follows (according to DarkDust):

arr.all? {|s| s =~ /^\d*$/ }




All Articles