理解按位或'|';在Ruby示例中
我当时正在用Ruby实现一个递归powerset算法,遇到了堆栈溢出的帖子理解按位或'|';在Ruby示例中,ruby,algorithm,bitwise-operators,Ruby,Algorithm,Bitwise Operators,我当时正在用Ruby实现一个递归powerset算法,遇到了堆栈溢出的帖子 def powerset(set) return [set] if set.empty? p = set.pop subset = powerset(set) subset | subset.map { |x| x | [p] } end powerset(['a']、['b']、['c'])-->[[]、[“a”]、[“b”]、[“a”、“b”]、[“c”]、[“a”、“c”]、[“b”、“c”
def powerset(set)
return [set] if set.empty?
p = set.pop
subset = powerset(set)
subset | subset.map { |x| x | [p] }
end
powerset(['a']、['b']、['c'])-->[[]、[“a”]、[“b”]、[“a”、“b”]、[“c”]、[“a”、“c”]、[“b”、“c”]、[“a”、“b”、“c”]
基本上,我无法理解最后一行。我知道这是“”运算符,我通常也知道它的作用,但我很难理解它在最后一行中是如何工作的
有人能告诉我在更容易阅读的Ruby中有什么等价物吗 这里有一个对应的更容易阅读的单词:)
实际上,当在数组上使用时,
|
是Ruby的运算符总是解析为方法。如果接收器为整数,则为按位或。但是对于数组,它是集合并集。如果您能告诉我们,set
文档的哪一部分您不清楚,那就太好了。这样,Ruby开发人员就可以为将来的读者改进文档。@JörgWMittag这与集合文档无关。看起来我错误地认为|
是位OR运算符,这导致我不理解它在这种情况下是如何工作的。既然|
实际上是数组
上的一个方法,那么同样的问题仍然存在:是什么让你认为数组|
是位OR?它的文档中是否有可以改进的地方?
If the set is empty:
return a list with one empty set
Remove an element from the set and call it "p"
Call "subset" the powerset of the new set (that excludes p)
Return the union of this new powerset and another
version of it, where p is added to each of its sets