views:

72

answers:

2

Hi,

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 common actual usage is & if its something I should fully understand.

Thanks, -J

A: 

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.

x1a4
Very interesting, I think I'll give it a miss for now...if I need it on a project will come back to this stuff then. Thanks
Jason
+1  A: 

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 (|).

Jörg W Mittag