Bit Banging in Ruby

Bit banging in ruby

If the underlying value is important then you can create a module that you use like an enum

module Groups
ADMIN = 1
BOSS = 2
CLERK = 4
MEAT = 8
BREAD = 16
CHEESE = 32
end

To set permissions just bitwise or them together

permissions = Groups::BOSS | Groups::MEAT | Groups::CHEESE

and to test you do a bitwise and

>> permissions & Groups::CHEESE > 0
=> true
>> permissions & Groups::BREAD > 0
=> false

I also like how you can make actual bitmasks more readable with _ like this

permissions = 0b0010_1010

Ruby bit banging, how to perform additive and negative

You'll want to use permissions &= ~mask:

irb > permissions = 0
# => 0
irb > permissions |= 512
# => 512
irb > permissions |= 256
# => 768
irb > permissions &= ~1
# => 768
irb > permissions &= ~256
# => 512
irb > permissions &= ~512
# => 0

Bit banging in ruby

If the underlying value is important then you can create a module that you use like an enum

module Groups
ADMIN = 1
BOSS = 2
CLERK = 4
MEAT = 8
BREAD = 16
CHEESE = 32
end

To set permissions just bitwise or them together

permissions = Groups::BOSS | Groups::MEAT | Groups::CHEESE

and to test you do a bitwise and

>> permissions & Groups::CHEESE > 0
=> true
>> permissions & Groups::BREAD > 0
=> false

I also like how you can make actual bitmasks more readable with _ like this

permissions = 0b0010_1010

Write two similar methods -one with bang, one without- while respecting DRY concept

You can also factor out the code for a single item, then be a little more verbose in the array methods. The left_outer_join_element() method here makes practical sense on its own and is reusable even for non-Array objects.

def left_outer_join(ary, &block)
self.map { |e| left_outer_join_element(e, ary, &block) }
end

def left_outer_join!(ary, &block)
self.map! { |e| left_outer_join_element(e, ary, &block) }
end

protected

def left_outer_join_element(element, ary, &block)
ary.each do |obj|
if yield element, obj
obj.keys.each do |key|
element[key] = obj[key]
end
break
end
end
element
end

Why can't I overwrite self in the Integer class?

You cannot change the value of self

An object is a class pointer and a set of instance methods (note that this link is an old version of Ruby, because its dramatically simpler, and thus better for explanatory purposes).

"Pointing" at an object means you have a variable which stores the object's location in memory. Then to do anything with the object, you first go to the location in memory (we might say "follow the pointer") to get the object, and then do the thing (e.g. invoke a method, set an ivar).

All Ruby code everywhere is executing in the context of some object. This is where your instance variables get saved, it's where Ruby looks for methods that don't have a receiver (e.g. $stdout is the receiver in $stdout.puts "hi", and the current object is the receiver in puts "hi"). Sometimes you need to do something with the current object. The way to work with objects is through variables, but what variable points at the current object? There isn't one. To fill this need, the keyword self is provided.

self acts like a variable in that it points at the location of the current object. But it is not like a variable, because you can't assign it new value. If you could, the code after that point would suddenly be operating on a different object, which is confusing and has no benefits over just using a variable.

Also remember that the object is tracked by variables which store memory addresses. What is self = 2 supposed to mean? Does it only mean that the current code operates as if it were invoked 2? Or does it mean that all variables pointing at the old object now have their values updated to point at the new one? It isn't really clear, but the former unnecessarily introduces an identity crisis, and the latter is prohibitively expensive and introduce situations where it's unclear what is correct (I'll go into that a bit more below).

You cannot mutate Fixnums

Some objects are special at the C level in Ruby (false, true, nil, fixnums, and symbols).

Variables pointing at them don't actually store a memory location. Instead, the address itself stores the type and identity of the object. Wherever it matters, Ruby checks to see if it's a special object (e.g. when looking up an instance variable), and then extracts the value from it.

So there isn't a spot in memory where the object 123 is stored. Which means self contains the idea of Fixnum 123 rather than a memory address like usual. As with variables, it will get checked for and handled specially when necessary.

Because of this, you cannot mutate the object itself (though it appears they keep a special global variable to allow you to set instance variables on things like Symbols).

Why are they doing all of this? To improve performance, I assume. A number stored in a register is just a series of bits (typically 32 or 64), which means there are hardware instructions for things like addition and multiplication. That is to say the ALU, is wired to perform these operations in a single clock cycle, rather than writing the algorithms with software, which would take many orders of magnitude longer. By storing them like this, they avoid the cost of storing and looking the object in memory, and they gain the advantage that they can directly add the two pointers using hardware. Note, however, that there are still some additional costs in Ruby, that you don't have in C (e.g. checking for overflow and converting result to Bignum).

Bang methods

You can put a bang at the end of any method. It doesn't require the object to change, it's just that people usually try to warn you when you're doing something that could have unexpected side-effects.

class C
def initialize(val)
@val = val # => 12
end # => :initialize

def bang_method!
"My val is: #{@val}" # => "My val is: 12"
end # => :bang_method!
end # => :bang_method!

c = C.new 12 # => #<C:0x007fdac48a7428 @val=12>
c.bang_method! # => "My val is: 12"
c # => #<C:0x007fdac48a7428 @val=12>

Also, there are no bang methods on integers, It wouldn't fit with the paradigm

Fixnum.instance_methods.grep(/!$/)  # => [:!]

# Okay, there's one, but it's actually a boolean negation
1.! # => false

# And it's not a Fixnum method, it's an inherited boolean operator
1.method(:!).owner # => BasicObject

# In really, you call it this way, the interpreter translates it
!1 # => false

Alternatives

  • Make a wrapper object: I'm not going to advocate this one, but it's the closest to what you're trying to do. Basically create your own class, which is mutable, and then make it look like an integer. There's a great blog post walking through this at http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html it will get you 95% of the way there
  • Don't depend directly on the value of a Fixnum: I can't give better advice than this without knowing what you're trying to do / why you feel this is a need.

Also, you should show your code when you ask questions like this. I misunderstood how you were approaching it for a long time.



Related Topics



Leave a reply



Submit