Skip to content

Commit 58c344c

Browse files
committed
initialize now takes string rather than length.
1 parent 159d93e commit 58c344c

File tree

3 files changed

+15
-19
lines changed

3 files changed

+15
-19
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Usage
2121
Bitwise assignment and retrieval:
2222

2323
```ruby
24-
b = Bitwise.new(1)
24+
b = Bitwise.new("\x00")
2525

2626
b.to_bits
2727
=> "00000000"

lib/bitwise.rb

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
class Bitwise
66
attr_accessor :value
77

8-
def initialize(size = 0)
9-
@value = "\x00" * size
8+
def initialize(value = "")
9+
@value = value.force_encoding(Encoding::ASCII_8BIT)
1010
end
1111

1212
def size
@@ -51,36 +51,32 @@ def get_byte(index)
5151
end
5252

5353
def not
54-
result = Bitwise.new
55-
result.value = Bitwise.string_not(self.value)
56-
result
54+
Bitwise.new(Bitwise.string_not(self.value))
5755
end
5856
alias :~ :not
5957

6058
def intersect(other)
61-
min, max = [ self.value, other.value ].sort_by{|i| i.bytesize }
62-
result = Bitwise.new
63-
result.value = Bitwise.string_intersect(max, min)
64-
result
59+
assign_max_and_min(other)
60+
Bitwise.new Bitwise.string_intersect(@max, @min)
6561
end
6662
alias :& :intersect
6763

6864
def union(other)
69-
min, max = [ self.value, other.value ].sort_by{|i| i.bytesize }
70-
result = Bitwise.new
71-
result.value = Bitwise.string_union(max, min)
72-
result
65+
assign_max_and_min(other)
66+
Bitwise.new Bitwise.string_union(@max, @min)
7367
end
7468
alias :| :union
7569

7670
def xor(other)
77-
min, max = [ self.value, other.value ].sort_by{|i| i.bytesize }
78-
result = Bitwise.new
79-
result.value = Bitwise.string_xor(max, min)
80-
result
71+
assign_max_and_min(other)
72+
Bitwise.new Bitwise.string_xor(@max, @min)
8173
end
8274
alias :^ :xor
8375

76+
def assign_max_and_min(other)
77+
@min, @max = [ self.value, other.value ].sort_by{|i| i.bytesize }
78+
end
79+
8480
def value=(string)
8581
@value = string.force_encoding(Encoding::ASCII_8BIT)
8682
@value.bytesize

spec/bitwise_spec.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
describe Bitwise do
77
before do
8-
@bitwise = Bitwise.new(1)
8+
@bitwise = Bitwise.new("\x00")
99
end
1010

1111
describe "assignment and retrieval" do

0 commit comments

Comments
 (0)