Reputation: 11649
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
Reputation: 110675
Four ways using String
methods:
str1 = '100100110'
str2 = '100100210'
str1.delete('01') == '' #=> true
str2.delete('01') == '' #=> false
str1.tr('01','') == '' #=> true
str2.tr('01','') == '' #=> false
str1.gsub(/[01]/,'') == '' #=> true
str2.gsub(/[01]/,'') == '' #=> false
str1.count('01') == str1.size #=> true
str2.count('01') == str2.size #=> false
Upvotes: 2
Reputation: 18762
Here is one way of doing this:
"101011".chars.all? {|x| x =~ /[01]/} # true if binary, else false
Upvotes: 0