check if a string contains only numbers in Ruby
Code snippet on how to check if a string contains only numbers in Ruby
def contains_numbers?(string)
string.match(/\A\d+\z/)
end
This Ruby code checks if a string contains only numbers. It defines a function called “contains_numbers?” which takes in one argument (a string). Inside the function, we use Ruby’s “match” method. The “match” method looks for a regular expression, in this case one that looks for numbers \d+ followed by the end of the string \z. If the string matches this expression, it returns a “MatchData” object, otherwise it will be nil. In other words, it returns true if the string only contains numbers and false if not.