简体   繁体   English

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

[英]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: 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. 链接查看方法。

| 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 . GL_COLOR_BUFFER_BITGL_DEPTH_BUFFER_BIT是积分常数( 0x000040000x00000100 ,分别地),并且该操作的结果为0x00000500 This is what is being passed into glClear - a single number, not multiple arguments. 这就是传递给glClear -一个数字,而不是多个参数。

One can use & (bit-AND) operator to tease out bits out of integers. 可以使用& (位与)运算符从整数中挑出位。 Eg 例如

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 (eg one might say my_method(:read, force: true) is clearer, and it is definitely simpler to use). 这在Ruby中不是很常见,因为我们有更好和更清晰的方式来做类似的事情(例如,可能会说my_method(:read, force: true)更清晰,并且使用起来肯定更简单)。 However, this is pretty standard in C, and Ruby OpenGL is a pretty thin wrapper over the C functions. 但是,这在C语言中是非常标准的,而Ruby OpenGL在C函数中是很薄的包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM