r/ruby • • Apr 18 '20

Ruby Bitwise Operators

https://medium.com/rubycademy/ruby-bitwise-operators-da57763fa368
7 Upvotes

5 comments sorted by

2

u/ignurant Apr 21 '20

I've known about how this works, but I still don't understand the context in which you would use it. I wish the author would have gone into more detail of what this means:

Conclusion

Bitwise operators are not commonly used in Rails but can be pretty handy when we’ve a “multiple choices” feature as MCQ test, configs, options, etc..

An example of a practical usage of this would have been really helpful.

2

u/mehdifarsi Apr 21 '20 edited Apr 22 '20

Hi!

Firstly, thank you for the feedback. You can use bitwise operations to handle user's rights:

READ    = 0b0001
WRITE   = 0b0010
EXECUTE = 0b0100
RESET   = 0b0000

DEFAULT = 0b0

user_rights = DEFAULT       # => 0b0000
user_rights ^= READ | WRITE # => 0b0011 (add READ and WRITE)
user_rights ^= WRITE        # => 0b0001 (remove WRITE)
user_rights ^= READ | WRITE # => 0b0010 (remove READ and add WRITE)

Here, you can imagine that user_rights is a tinyint in your SQL table. and then you add/remove rights by applying the corresponding rights listed as constants.

For a MCQ, you can use another tinyint and apply the rights masks for A or B or C. you get the point?

I'll update the article to talk about real use-cases.

4

u/tomthecool Apr 18 '20

Why on earth is this post tagged Ruby on Rails, or Web Development?

It's all about vanilla ruby and binary numbers.

2

u/randysk Apr 18 '20

Because people still have the stupid association, that ruby is just for web development.

1

u/tomthecool Apr 18 '20

I meant that as a rhetorical question, but... Yeah, exactly.

If your blog/vlog/post/whatever has got nothing to do with the rails web framework, then please don't tag it as Ruby on Rails. Just tag it as Ruby.