Sal-laS
Sal-laS

Reputation: 11649

Check if string has only `0` and `1`

I am supposed to get a string and make sure that it represents a binary number like "101011".

This question deals with hexadecimal strings, but I do not know how I should replace the letter H in the regex in statement !str[/\H/]. Could you help me?

Upvotes: 0

Views: 3664

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Four ways using String methods:

str1 = '100100110'
str2 = '100100210'

String#delete

str1.delete('01') == '' #=> true
str2.delete('01') == '' #=> false

String#tr

str1.tr('01','') == '' #=> true
str2.tr('01','') == '' #=> false

String#gsub

str1.gsub(/[01]/,'') == '' #=> true
str2.gsub(/[01]/,'') == '' #=> false

String#count

str1.count('01') == str1.size #=> true
str2.count('01') == str2.size #=> false

Upvotes: 2

Wand Maker
Wand Maker

Reputation: 18762

Here is one way of doing this:

"101011".chars.all? {|x| x =~ /[01]/} # true if binary, else false

Upvotes: 0

sawa
sawa

Reputation: 168091

A straightforward way using regex is:

"101011" !~ /[^01]/

Upvotes: 4

Related Questions