From: "David A. Black" Date: 2009-01-29T11:16:21+09:00 Subject: Re: Bitwise question Hi -- On Thu, 29 Jan 2009, Rob Biedenharn wrote: > > On Jan 28, 2009, at 4:32 PM, Pascal J. Bourguignon wrote: > >> Andrew Barringer writes: >> >>> I'm working on a project that has a bitmap of permissions and I need to >>> find out if a user has access. >>> >>> >>> >>> Given permissions bit mask of 0001C0200F02000000000 where each bit >>> represents a specific permission >>> >>> >>> >>> And a request for permissions check on bits [37, 12, 48] >>> >>> >>> >>> What's the best way to find out if user has access to all requested >>> permissions? >> >> >> (def check(permissions,bits) >> (bits . inject(true) { | r , b | >> (r and (0 != (permissions & (1 << b)))) >> }) >> end) >> nil >> (check 0xf0,[1,4,5,6]) -> false >> (check 0xf0,[4,5,6]) -> true >> >> -- >> __Pascal Bourguignon__ > > Or a simpler version: > > class Integer > def as_bits > ary = [] > (self.size*8).times {|i| ary.unshift(i) if self[i].nonzero?} > ary > end > > def check_permissions(*bits) > bits.all? {|bit| self[bit].nonzero? } > end > end Thanks for the reminder about Integer#[], one of those cool Ruby things that come back and re-surprise me with their coolness occasionally :-) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!