如何使用|将多个参数传递给Ruby方法

And*_*rek 1 ruby opengl

我看到了这个方法得到参数的方式,并想知道如何复制它.

红宝石/ OpenGL的:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
Run Code Online (Sandbox Code Playgroud)

我试过这个:

def my_method(*args)
    puts args
end
my_method(0 | 1) #=> 1
Run Code Online (Sandbox Code Playgroud)

但它不起作用.谢谢你的阅读!

链接以查看方法.

Ama*_*dan 5

|是一个有点参数.GL_COLOR_BUFFER_BIT并且GL_DEPTH_BUFFER_BIT是整数常量(0x000040000x00000100,分别),操作的结果是0x00000500.这是传递给的glClear- 一个数字,而不是多个参数.

可以使用&(位-AND)运算符来排除整数位.例如

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
Run Code Online (Sandbox Code Playgroud)

这在Ruby中并不常见,因为我们有更好更清晰的方法来做类似的事情(例如,人们可能会说my_method(:read, force: true)更清楚,使用起来更简单).但是,这在C语言中非常标准,而Ruby OpenGL是C函数的一个非常薄的包装器.