Ruby bit by bit or

Here is the code

def tmp

  a = ancestors.first(ancestors.index(ActiveRecord::Base))

  b = a.sum([]) { |m| m.public_instance_methods(false) | 
                  m.private_instance_methods(false) | 
                  m.protected_instance_methods(false) }

  b.map {|m| m.to_s }.to_set

end

      

I thought | is a bitwise OR operator. So how does b contain non-boolean values?

-1


source to share


1 answer


It would help if you said what your code was supposed to do, but I think I finally got it. |

which you have is not OR, neither bitwise nor logical. This is an array concatenation operation. Check it out under Array rubydoc. It takes Array arguments and gives the result of an array consisting of all the elements found in any array.

Since almost everything in Ruby is an object (except for blocks, which are irrelevant here), there are no absolute "operators" other than a simple assignment. Each operator is in fact a method defined on some class and therefore contextual.



Also, as someone rightly pointed out (removed now), Bitwise OR is dealing with whole numbers, not with boolean: 7 | 12 == 15

. Boolean or ||

deals with boolean values, but it can also return non-boolean, since strictly speaking everything except nil

and false

is true. Thus, it 7 || 12

returns 7

rather than true

(which is still equivalent to true in most contexts).

UPDATE: I overlooked the fact that ||

and &&

when used in a boolean object actually cannot be defined in Ruby due to their short-circuit semantics. This, however, does not change the fact that they behave like boolean methods.

+4


source







All Articles