(def check(permissions,bits)
(bits . inject(true) { | r , b |
(r and (0 != (permissions & (1 << b))))
})
end)
That what happens when one spends his time typing parenthesis instead of
programming, my dear Pascal. I managed to count at least two bugs there.
One, you need to do (1 << (b-1)). Two, if you pass [] as the bits, the
result will be ‘true’.
One, you need to do (1 << (b-1)).
Bit 0 is the first bit. 2^0 = 1
Two, if you pass [] as the bits, the
result will be ‘true’.
Which is of course the correct answer.
All the bits in the empty set are in any bitfield.
There is no bit in the empty set hat are not in a given bitfield.
One, you need to do (1 << (b-1)).
Bit 0 is the first bit. 2^0 = 1
I stand corrected.
Two, if you pass [] as the bits, the
result will be ‘true’.
Which is of course the correct answer.
All the bits in the empty set are in any bitfield.
There is no bit in the empty set hat are not in a given bitfield.
All right, all right, you win I now see that [].all? too returns
‘true’.
(So my attempt at dissuading you from using parenthesis failed
miserably. Say, won’t you consider dropping them for humanitarian
reasons?)
def check_permissions(*bits)
bits.all? {|bit| self[bit].nonzero? }
end
end
Simplier? A class, two methods, a lot of operations, a lot of memory!
as_bits is just there to provide information for the sake of
understanding the examples. check_permissions is Rob’s answer to the
original question. It looks about as simple as it could be: very
idiomatic, clear, and concise.
If you don’t like adding to Integer you can make it functional-style
by adding a second argument.
Which is of course the correct answer.
All the bits in the empty set are in any bitfield.
There is no bit in the empty set hat are not in a given bitfield.
All right, all right, you win I now see that [].all? too returns
‘true’.
I could imagine wanting to handle the [] case conservatively. If the
idea is to screen for permissions, and you want the default to be
rejecting the person, then you’d probably want to reject an empty set
of bits. [].all? does indeed always return true, so you’d have to do a
separate empty? test somewhere.
Thanks guys, the answers provided contained what I was looking for. I
had hacked together something that worked but seemed so un-ruby like.
This is nice looking very fast code.
Andy
From: Clifford H. [mailto:[email protected]]
Sent: Wed 1/28/2009 10:37 PM
To: ruby-talk ML
Subject: Re: Bitwise question
David A. Black wrote:
Thanks for the reminder about Integer#[], one of those cool Ruby
things that come back and re-surprise me with their coolness
occasionally
Cool indeed… pity it doesn’t take a range however:
9547[0…-1]
TypeError: can’t convert Range into Integer
oops.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.