Ruby:片段:(num& 1)== 0到底是做什么的? [英] Ruby: What does the snippet: (num & 1) == 0 exactly do?
问题描述
我正在观看来自PragProg的元编程视频,戴夫·托马斯(Dave Thomas)显示了以下代码段:
I was watching a metaprogramming video from PragProg, and Dave Thomas showed this snippet of code:
module Math
class << self
def is_even?(num)
(num & 1) == 0 # What exactly is going on here? Particularly (num & 1)
end
end
end
puts Math.is_even? 1 # => false
puts Math.is_even? 2 # => true
现在我了解这里发生了什么,但我不知道 Math.is_even的
类方法.我知道这是按位操作,仅此而已.有人可以向我解释该代码行的含义吗?谢谢.(num& 1)
部分到底发生了什么?
Now I understand what is going on here, but I don't know what exactly is happening with the (num & 1)
part of the Math.is_even?
class method. I know it is a bitwise operation but that is about it. Can someone explain to me what is going with that line of code? Thanks.
推荐答案
&
是按位AND运算符.进行(num& 1)
检查该数字的最后一位(最低有效位)是否已设置.如果已设置,则数字为奇数;如果未设置,则数字为偶数.
&
is a bitwise AND operator. Doing (num & 1)
checks if the last bit (least significant bit) of the number is set. If it is set, the number is odd, and if it is not set, it is even.
这只是检查数字是偶数还是奇数的快速方法.
It is just a fast way to check if a number is even or odd.
您可以在此处查看红宝石按位运算符的列表: http://www.techotopia.com/index.php/Ruby_Operators#Ruby_Bitwise_Operators
You can see a list of the ruby bitwise operators here: http://www.techotopia.com/index.php/Ruby_Operators#Ruby_Bitwise_Operators
这篇关于Ruby:片段:(num& 1)== 0到底是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!