In “The Ruby Way” on p.80
Hal Fulton provides this String method for .bin,
(to go along with .oct and .hex) [1.6.7]
class String
def bin
val = self.strip
pattern= /^([±]?)(0b)?([01]+)(.*)$/
parts = pattern.match(val)
return 0 if not parts
sign = parts[1]
num = parts[3]
eval(sign + “0b” + num)
end
end
These examples were given.
a = “10011001”.bin # 153
b = “0b10011001”.bin # 153
c = “0B1001001”.bin # 0
d = “nothing”.bin # 0
e = “0b100121001”.bin # 9
Here’s a shorter version which produces the same output.
class String
def bin
val = self.strip
val[0,2] == “0b” ? val.oct : (“0b”+val).oct
end
end
- Since “0B1010101”.oct and "0b1010101.oct, produce the
same output, shouldn’t “0B”+val allow a valid conversion
from binary to decimal also?
Here’s another pearl, er, ruby for your toolkit.
I needed this to convert binary strings to hex strings.
Example: “100110110101” => “9b5”
class String
def b2h
val = self.strip
sprintf("%x", (val[0,2] == “0b” ? val.oct : (“0b”+val).oct))
end
end
Here are some examples:
“10101010101”.b2h # "555"
“0b111101001100”.b2h # “f4c”
“0B101010”.b2h # "0"
“182834”.b2h # “1”
- What’s a better, more Rubyish, name for b2h, if any?
Jabari Zakiya