0

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

Jason
  • 22,645
  • 5
  • 29
  • 51

2 Answers2

1

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
  • 19,417
  • 5
  • 40
  • 40
  • 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 May 14 '10 at 05:10
1

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

Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653