Arrays in Ruby, how to deal with this situation?
2 answers
If blank lines are allowed:
def contains_non_digit(array)
!array.select {|s| s =~ /^.*[^0-9].*$/}.empty?
end
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.
+2
source to share
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*$/ }
+8
source to share