What is the difference between '&&' and '&' in Ruby - ruby

Recently, I observed a very interesting result in Ruby while making use of && and & for the input combination of 0 & 1.
Can someone please explain the below output with respect to the above mentioned two operators? The below is implemented using Ruby 2.0.0-p451
2.0.0-p451 :006 > 0 && 1
=> 1
2.0.0-p451 :008 > 0 & 1
=> 0
Thank you

&& is the logical AND operator. It will be truthy, IFF both operands are truthy. And it is lazy (aka short-circuiting), which means it will stop evaluating as soon as the result has been fully determined. (So, since both operands need to be truthy, if the first operand is falsy, you already know that the result is going to be falsy, without even evaluating the second operand.) It will also not just return true or false, but rather return the operand which determines the outcome. IOW: if a is falsy, it'll return a, otherwise it'll return b:
nil && (loop {})
# => nil
# Note: the infinite loop is *not* evaluated
# Note: the return value is nil, not false
true && nil
# => nil
true && 'Hello'
# => 'Hello'
& simply calls the method &. It will do whatever the object wants it to do:
def (weirdo = Object.new).&(other)
puts 'Whoah, weird!'
'Hello, ' + other
end
weirdo & 'World'
# Whoah, weird!
# => 'Hello, World'
In general, & and its brother | are expected to perform conjunction and disjunction. So, for booleans, they are perform AND and OR (TrueClass#&, FalseClass#&, NilClass#&, TrueClass#|, FalseClass#|, NilClass#|) with the exception that & and | are standard method calls and thus always evaluate their argument and that they always return true or false and not their arguments.
For Sets, they perform set intersection and set union: Set#&, Set#|. For other collections (specifically Arrays), they also perform set operations: Array#&, Array#|.
For Integers, they perform BITWISE-AND of the two-complement's binary representation: Fixnum#&, Bignum#&, Fixnum#|, Bignum#|.

&& is a boolean and. It returns the second argument if the first argument is true-ish. Because 0 is true-ish in Ruby, 1 is returned.
& is a bitwise and. It compares the bit representation of the values. Because (imaging 8 bit) 00000000 (0) and 00000001 (1) have no 1 digits in common, 00000000 (0) is returned.

This page gives a good explanation of the different operators in Ruby.
&& is logical AND operator in ruby.
> a = true
> b = true
> c = false
> a && b
=> true
> a && c
=> false
& is the bitwise AND operator in ruby. Per the wikipedia article on the description for the "bitwise AND operator":
A bitwise AND takes two binary representations of equal length and
performs the logical AND operation on each pair of corresponding bits.
The result in each position is 1 if the first bit is 1 and the second
bit is 1; otherwise, the result is 0.

One is a boolean operator, the other is a bitwise operator:
# Bitwise operators
a = 78 # 01001110
b = 54 # 00110110
puts (a&b) # 00000110 = 6
puts (a|b) # 01111110 = 126
puts (a^b) # 01111000 = 120
puts (~a) # 10110001 = -79
puts (a<<2) # 00111000 = 312
puts (a>>2) # 00010011 = 19
http://www.public.traineronrails.com/courses/ruby/pages/008-rubyoperators.html

&& is logical and. Which is to say, a && b returns true if a is true and b is true. & is bitwise and. In (almost) any other language, logical and of 0 and 1 would be 0, because (almost) all other languages consider 0 to be false. But in ruby, anything except nil and false are considered to be truthy.

&& is a Logical operator which will always return a boolean value.
z It's either true if both of the values are true
true && true
and will return false if any of the value is false
false && true
Now comes to second point & Operator.
Here are two answer for the & Operator.
& is a Bitwise operator as mentioned in above answers, It compares bit representation in the form of 0 and 1.
Another Important answer is, In upgradation of Ruby 2.6 its implementation is somewhat modified.
& is represented as intersection operator
For ex:
[1, 2, 3] & [2, 3, 4]
$ [2, 3]

Related

Create a method to find if a number is a power of 2?

I have this code to return true if num is a power of 2.
def is_power_of_two?(num)
result = num.inject(0) {|n1, n2| n2 ** n1}
if result == num
true
else
false
end
end
p is_power_of_two?(16)
I keep getting an error though. How could I fix and simplify this code?
Clearly, n is a non-negative integer.
Code
def po2?(n)
n.to_s(2).count('1') == 1
end
Examples
po2? 0 #=> false
po2? 1 #=> true
po2? 32 #=> true
po2? 33 #=> false
Explanation
Fixnum#to_s provides the string representation of an integer (the receiver) for a given base. The method's argument, which defaults to 10, is the base. For example:
16.to_s #=> "16"
16.to_s(8) #=> "20"
16.to_s(16) #=> "10"
15.to_s(16) #=> "f"
It's base 2 we're interested in. For powers of 2:
1.to_s(2) #=> "1"
2.to_s(2) #=> "10"
4.to_s(2) #=> "100"
8.to_s(2) #=> "1000"
16.to_s(2) #=> "10000"
For a few natural numbers that are are not powers of 2:
3.to_s(2) #=> "11"
5.to_s(2) #=> "101"
11.to_s(2) #=> "1011"
We therefore wish to match binary strings that contain one 1.
Another Way
R = /
\A # match beginning of string ("anchor")
10* # match 1 followed by zero or more zeroes
\z # match end of string ("anchor")
/x # free-spacing regex definition mode
def po2?(n)
(n.to_s(2) =~ R) ? true : false
end
po2?(4) #=> true
po2?(5) #=> false
And one for the road
This uses Fixnum#bit_length and Fixnum#[]:
def po2?(n)
m = n.bit_length-1
n[m] == 1 and m.times.all? { |i| n[i].zero? }
end
po2? 0 #=> false
po2? 1 #=> true
po2? 32 #=> true
po2? 33 #=> false
Try:
def is_power_of_two?(num)
num != 0 && (num & (num - 1)) == 0
end
It is well explained here (for C#, but #GregHewgill's explanation applies here as well)
I would do something like this, using Ruby's Math module.
def power_of_two?(n)
Math.log2(n) % 1 == 0
end
Or, if you wanted to be really cool:
def power_of_two?(n)
(Math.log2(n) % 1).zero?
end
Some IRB output:
2.1.0 :004 > power_of_two?(2)
=> true
2.1.0 :005 > power_of_two?(32768)
=> true
2.1.0 :006 > power_of_two?(65536)
=> true
This method assumes that the input is a positive integer.
Source
Another way to solve this is to go the other way around than most of the answers here - we can use the number 1 to start and find out if the number is the power of two. Like this:
def power_of_two?(num)
product = 1
while product < num
product *= 2
end
product == num
end
We start with 1. Then we multiply the 1 by 2, and keep multiplying by 2 until the product is larger than num (product < num). Once we hit that condition, we stop, exit the loop, and check if it's equal to num (product == num). If it is, the num is the power of 2.
As was pointed out in the comments above, you were getting errors because you're trying to use the inject method on a non-iterable (an int). Here's a solution using the suggested log2
def is_power_of_two?(num)
result = Math.log2(num)
result == Integer(result)
end
Note: will fail with very big numbers close to binaries (like 2 ^ 64 - 1). A foolproof version (but slower) would be:
def is_power_of_two?(num)
while (num % 2 == 0 and num != 0)
num /= 2
end
num == 1
end
Please comment any improvements that any of you may find.
Here is another solution that uses recursion:
def power_of_2?(number)
return true if number == 1
return false if number == 0 || number % 2 != 0
power_of_2?(number / 2)
end
In my opinion, the easiest -- but maybe a little long -- way of doing what you need to do is just writing this recursive method like so:
def power_of_two?(number)
continue = true
if number == 1
return true
end
if number % 2 != 0
return false
else
while continue == true do
if number.to_f / 2.0 == 2.0
continue = false
return true
else
if number % 2 != 0
continue = false
return false
else
number /= 2
continue = true
end
end
end
end
end
One is a power of two (2^0), so it first checks if the number given is 1. If not, it checks if it is odd, because 1 is the only odd number that is a power of two.
If it is odd it returns false and moves on to the else statement. It will check if the number divided by 2 is two, because then it would obviously be a power of 2. It does this as a float, because 5/2 in Ruby would return 2.
If that is false, it then again checks if the number is odd -- unnecessary on the first round, necessary after that. If the number is not odd, it will divide the number by two and then do the loop another time.
This will continue until the program resolves itself by getting 2 or any odd number, and returns true or false, respectively.
I ran into this one in a bootcamp application prep. I'm not a math person and don't understand a few of these methods, so I wanted to submit a common sense approach for people like me. this requires little knowledge of math, except to know a number to the second power will be the result of some number multiplied by itself.
def is_power_of_two?(num)
num.times {|n| return true if (n+1) * (n+1) == num}
false
end
this method counts up to the num variable starting at 1 and returns true if (any of those numbers in the sequence multiplied by itself) is equal to num & if num is not 0 (more on that below).
example:
num = 9
1 * 1 == 9 #=> false
2 * 2 == 9 #=> false
3 * 3 == 9 #=> true
true is returned and method is finished running.
the #times method requires an integer > 0, so this edge case is "handled" by virtue of the fact that #times does nothing with "0" as the variable and returns false when outside of the #times iteration.
def power_of_two?(num)
num.to_s(2).scan(/1/).length == 1
end

Ruby: How to check for negative zero

How can I find out if a Float value is a negative zero (and not a positive one)?
Unfortunately:
-0.0 == 0.0 # => true
-0.0 === 0.0 # => true
My initial solution works but is ugly:
x.to_s == '-0.0'
From this question, I found
x == 0 and 1 / x < 0
Is there a better, more Ruby-like way?
Ruby's BigDecimal class has a sign method that produces the correct result for negative zero. You can convert a Float to a BigDecimal with the to_d method if you require 'bigdecimal/util'.
require 'bigdecimal'
require 'bigdecimal/util'
0.0.to_d.sign
#=> 1
-0.0.to_d.sign
#=> -1
Combine this with zero? and you're good to go:
def negative_zero?(x)
x.zero? && x.to_d.sign == -1
end
negative_zero?(0.0)
#=> false
negative_zero?(-0.0)
#=> true
The angle method (and it's aliases arg and phase) returns zero for positive floats and Pi for negatives.
p 0.0.angle #=> 0
p -0.0.angle #=> 3.141592653589793
In Ruby the Float equality operator for -0.0 and 0.0 returns true, as per ordinary arithmetic.
However if you convert the two floats to bytes using little-endian or big-endian byte order, you'll see they do not in fact match.
[-0.0].pack('E')
#=> "\x00\x00\x00\x00\x00\x00\x00\x80"
[0.0].pack('E')
#=> "\x00\x00\x00\x00\x00\x00\x00\x00"
[-0.0].pack('E') == [0.0].pack('E')
#=> false
If your purpose is to prevent "negative zero", then this is how rails does it:
number = number.abs if number.zero?
Cause ruby determines them as the same object the only way to detect it by "-" sign after string conversion, as you described: -0.0.to_s.start_with?('-').

Operator <=> in Ruby [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the Ruby <=> (spaceship) operator?
I saw a code and an operator I'm unfamiliar with
#array << {:suffix=> substring, :index => i}
#array.sort! { |x,y| x[:suffix] <=> y[:suffix]}
I can't do google on it. What does <=> do?
This is the spaceship operator, it was borrowed from Perl. It is commonly used for sorting, because it returns -1 if left operand is less than right operand, 1 if right operand is greater than the left and returns 0 otherwise.
1 <=> 2 # => -1
2 <=> 1 # => 1
1 <=> 1 # => 0
It does comparison defined for the particular class. If it is the case that ... < ... is true, it returns -1, if ... == ... is true, then 0, and if ... > ... is true, then 1.
It's called the spaceship operator.
For the core numeric and string classes, it's a comparison operator that returns -1, 0, or 1.
In theory, a class can define any operator to do anything it wants, but this will be the method that is used when sorting. It may make sense to define <=> for an arbitrary application class if that class will ever need to be ordered.

"Or" in If Blocks in Ruby

So I am writing a Ruby program for school that changes the value of a boolean to true if a certain value is either 1 or 3, and to false if it is 0 or 2. Since I come from a Java background, I thought that this code should work: if n == 1 || n == 3
But it does not. So my question here is is it possible to use an "Or" expression thingy in If blocks in Ruby? I know that my current situation could be solved easily by just something like the following:
if n == 0
t_o_f = false
elsif n == 1
t_o_f = true
Et Cetera. But I want to know if I can use an Or in If blocks for the future.
Yes, any expression can be used in an if condition, including those using the || (logical or) operator.
As with Java, Ruby's || operator short-circuits. That is, if the left side is true, the right side is not evaluated.
Idiomatic ruby uses postfix if for one-liners:
puts "Yes" if n == 4 || n == 5
Avoid postfix if the line is long, however, and break it into multiple lines:
if n == 4 || n == 5
puts "This is a big long string to be output....................."
end
That's because postfix if can get visually lost at the end of a long line.
You can have a one-liner with prefix if, but it's not commonly seen:
if n == 4 || n == 5 then puts "foo" end
or, perhaps:
if n == 4 || n == 5 ; puts "foo" ; end
This is really a multi-line if condensed into one line; the semicolons act as line breaks.
When testing for multiple conditions, it can sometimes be valuable to use Array#include?:
puts "foo" if [4, 5].include?(n)
The value of this for only two conditions is not that great. For three or more, it reads well.
The or operator works, and you can write the keyword too:
if n==1 or n==2
end
http://www.tutorialspoint.com/ruby/ruby_operators.htm
And you could also write what you want this way:
x = (n%2) ? true : false
In addition to #Wayne Conrad: if there is little or no 'logic' deciding if n is true or false, then this is also a good option:
result = case n
when 1, 3 then true
when 0, 2 then false
end

Ruby Equal to vs Comparison;

I need help for understanding - What is the difference between Equal to and Comparison?
Here is the case
x == y means `Equal to`
x = 10 and y = 10
puts "X and Y are equal" if x == y
puts "X and Y are equal" if x <=> y
I know when and where can I use equal to, but when and where can I use Comparison <=>
Thanks
When you want to compare? It returns -1, 0, 1. For example, sorting users by first name:
users_by_first = users.sort { |u1, u2| u1.fname <=> u2.fname }
Here's another SO question asking about the spaceship operator.
<=> General comparison operator. Returns -1, 0, or +1, depending on whether its receiver is less than, equal to, or greater than its argument.
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html
This is useful for sorting, for one thing.
Equality operators: == and !=
The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.
"koan" == "koan" # Output: => true
The != operator, AKA inequality or bang-tilde, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.
"koan" != "discursive thought" # Output: => true
Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.
When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.
2 == 2.0 # Output: => true
Comparison operators
Objects such as numbers and strings, which can be compared (amongst themselves) in terms of being greater or smaller than others, provide the <=> method, also known as the spaceship method. When comparing two objects, <=> returns -1 if the first object is lesser than the second (a < b), 0 in case they are equal (a == b) and 1 when the first object is greater than the second (a > b).
5 <=> 8 # Output: => -1
5 <=> 5 # Output: => 0
8 <=> 5 # Output: => 1
Most comparable or sortable object classes, such as Integer, Float, Time and String, include a mixin called Comparable, which provides the following comparison operators: < (less than), <= (less than or equal), == (equal), > (greater than), >= (greater than or equal). These methods use the spaceship operator under the hood.
Comparison operators can be used in objects of all the above classes, as in the following examples.
# String
"a" < "b" # Output: => true
"a" > "b" # Output: => false
# Symbol
:a < :b # Output: => true
:a > :b # Output: => false
# Fixnum (subclass of Integer)
1 < 2 # Output: => true
2 >= 2 # Output: => true
# Float
1.0 < 2.0 # Output: => true
2.0 >= 2.0 # Output: => true
# Time
Time.local(2016, 5, 28) < Time.local(2016, 5, 29) # Output: => true
When comparing numbers of different classes, comparison operators will implicitly perform simple type conversions.
# Fixnum vs. Float
2 < 3.0 # Output: => true
2.0 > 3 # Output: => false
More info about Ruby operators is available at this blog post.

Resources