Andrek
Andrek

Reputation: 105

How do I pass multiple arguments to a Ruby method using |

I saw the way it gets arguments this method and wanted to know how to replicate it.

Ruby/OpenGL:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

I tried with this:

def my_method(*args)
    puts args
end
my_method(0 | 1) #=> 1

But it does not work. Thanks for read!

Link to see the method.

Upvotes: 1

Views: 52

Answers (1)

Amadan
Amadan

Reputation: 198418

| is a bit-OR argument. GL_COLOR_BUFFER_BIT and GL_DEPTH_BUFFER_BIT are integer constants (0x00004000 and 0x00000100, respectively), and the result of the operation is 0x00000500. This is what is being passed into glClear - a single number, not multiple arguments.

One can use & (bit-AND) operator to tease out bits out of integers. E.g.

WRITE = 1
READ = 2
FORCE = 4
def my_method(code)
  puts "write" if code & WRITE != 0
  puts "read" if code & READ != 0
  puts "force" if code & FORCE != 0
end

my_method(READ | FORCE)
# => read
# => force

This is not very usual in Ruby, as we have better and clearer ways to do similar things (e.g. one might say my_method(:read, force: true) is clearer, and it is definitely simpler to use). However, this is pretty standard in C, and Ruby OpenGL is a pretty thin wrapper over the C functions.

Upvotes: 5

Related Questions