I am really new to ruby and want know if it's possible to check if a string contains only positive numbers using regex or some other function?
str = "123abcd" #return false because it contains alphabets
str = "153" #return true because of all numbers
The positive?() is an inbuilt method in Ruby returns a boolean value. It returns true if the number is a positive one, else it returns false.
In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.
The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .
Python Code: n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")
All other answers so far using regex are inefficient.
"123abcd" !~ /\D/ # => false
"153" !~ /\D/ # => true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With