开发者

With Ruby, where to use NOT, AND, OR, XOR operations for Fixnum or Bignum?

开发者 https://www.devze.com 2022-12-30 11:13 出处:网络
Just wondering if anyone has any realworld examples or know when you might use the NOT, AND, OR, XOR, <<, >> operators in Ruby.

Just wondering if anyone has any realworld examples or know when you might use the NOT, AND, OR, XOR, <<, >> operators in Ruby.

I've been programming for 4 years and never come across the need to use any of these, wondering how commo开发者_如何学编程n actual usage is & if its something I should fully understand.

Thanks, -J


xor (aka ^), <<, and >> are more often used in lower-level programming. A C programmer will be intimately familiar with what these do. I'm writing an emulator in Ruby currently and use << and >> often in the 6502 core due to things like it having a 1 byte word size but 2 byte pc. You need to do bit shifting to save the pc onto the stack, for example.

not, and, and or are variations of !, &&, and ||, respectively. They work the same, but have a 'looser binding' to the variables around them. Their use (at least in practice) is to allow writing of expressions with fewer parens. I believe Rails actually forbids the use of these operators completely within its own codebase due to misunderstandings about how they work.


In an answer to another question, I was forced to do some bit-twiddling to work around a missing feature in the String#unpack / Array#pack pair of APIs. It uses left-shift (<<) and bitwise-or (|).

0

精彩评论

暂无评论...
验证码 换一张
取 消