Tripon
Tripon

Reputation: 81

How can I validate that a string holds only zeroes and ones?

I have a string which should ONLY be made up of 0 and 1. If the string has any other characters (including special characters) then the validation should return false; otherwise it should return a true.

How can I achieve this?

Upvotes: 0

Views: 127

Answers (5)

steenslag
steenslag

Reputation: 80065

def binary?
  str.count("^01").zero?
end

Upvotes: 0

Michael Kruglos
Michael Kruglos

Reputation: 1286

Another way to do it:

str.chars.any?{|c| c!='0' && c!='1'}

Upvotes: 0

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

The following assumes your method will always receive a string; it doesn't perform any coercion or type checking. Feel free to add that if you need it.

def binary? str
  ! str.scan(/[^01]/).any?
end

This will scan the string for any characters other than zero or one using String#scan, and then returns an inverted Boolean that evaluates to false if Enumerable#any? is true, meaning that other characters are present in the string. For example:

binary? '1011'
#=> true

binary? '0b1011'
#=> false

binary? '0xabc'
#=> false

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

Use Regexp#===

s = '11er0'
# means other character present except 1 and 0
/[^10]/ === s # => true 

s = '1100'
# means other character not present except 1 and 0
/[^10]/ === s # => false

Here is a method :

def only_1_and_0(s)
  !(/[^10]/ === s)
end

only_1_and_0('11012') # => false
only_1_and_0('1101') # => true

Upvotes: 3

Erez Rabih
Erez Rabih

Reputation: 15788

try this:

def only_0_and_1(str)
  return !!(str =~ /^(0|1)+$/)
end

Upvotes: 1

Related Questions