From: "David A. Black" Date: 2009-01-29T11:21:33+09:00 Subject: Re: Bitwise question On Thu, 29 Jan 2009, Pascal J. Bourguignon wrote: > Rob Biedenharn writes: > >> On Jan 28, 2009, at 4:32 PM, Pascal J. Bourguignon wrote: >> >>> Andrew Barringer writes: >>> >>>> 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 >> 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 > > 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. 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!