Bit banging in ruby

随声附和 提交于 2019-12-04 13:53:28

问题


I want to create a bit, that will contain security permissions for a given user.

In c#, I would do this by creating an enumeration, and then I would do some bit banging on the binary value, by anding '&&' to see if it results in a TRUE value.

How can I do this best in Ruby?


回答1:


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



回答2:


Bitwse operations are trivial in Ruby.

> 1 | 2 # Create a bitmask from permission 2^0 + 2^1
=> 3

> 3 & 1 == 1 # See if the bitmask contains the 2^0 permission
=> true

> 3 & 4 == 4 # See if the bitmask contains the 2^2 permission
=> false



回答3:


Ryan Bates talks about using bitwise operations for embedding associations in this podcast. You can read text version here.



来源:https://stackoverflow.com/questions/3867714/bit-banging-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!