Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains only positive numbers in Ruby [closed]

Tags:

string

ruby

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
like image 973
user3187131 Avatar asked Feb 16 '14 16:02

user3187131


People also ask

How do you check if a number is positive in Ruby?

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.

How do I check if a string is in Ruby?

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.

How do you check if a value is an integer in Ruby?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How to check if a number is positive integer in python?

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. ")


1 Answers

All other answers so far using regex are inefficient.

"123abcd" !~ /\D/ # => false
"153" !~ /\D/     # => true
like image 152
sawa Avatar answered Sep 24 '22 16:09

sawa