Skip to content

Instantly share code, notes, and snippets.

@boddhisattva
Last active August 29, 2015 13:56
Show Gist options
  • Save boddhisattva/9086551 to your computer and use it in GitHub Desktop.
Save boddhisattva/9086551 to your computer and use it in GitHub Desktop.
Operators in Ruby - Part 1
true
16
24 -16 80 5 0
22
22
2
2
hello world
hello world
1
0
-1
-12
1
value of a1 is: 24 and value of a2 is: -16
false
true
false
true
1
# Playing with operators in Ruby
limit = 5
p = 2 * Math.sqrt(4) < limit
puts(p)
k = 2 ** 4 # Exponentiation Operator..
puts(k)
#--------------------------------------------------------------------------------------------------------------------------------
t = 4
l = 20
a1 = t + l
a2 = t - l
a3 = t * l
a4 = l / t
a5 = 20 % 4
puts("\n#{a1}\t#{a2}\t#{a3}\t#{a4}\t#{a5}\n")
#--------------------------------------------------------------------------------------------------------------------------------
# Left and Right Shift operators..
b1 = 11 << 1
b2 = 11 >> -1 # !! check the working of this..
puts(b1)
puts(b2)
b3 = 22 >> 3
b4 = 22 << -3 # !! check the working of this..
puts(b3)
puts(b4)
#--------------------------------------------------------------------------------------------------------------------------------
# Right Shift operator also used for appending..also use of STDOUT Predefined Global constant..
message = "hello"
messages = []
message << " world"
puts(message)
STDOUT << message
print("\n")
#--------------------------------------------------------------------------------------------------------------------------------
# working of AND, OR, Tilde(~) and XOR
c1 = 0 | 1
puts(c1)
c2 = 0 & 1
puts(c2)
c3 = ~0 # ~ for a variable x it functions as -x-1.. here its -0-1 thus op is c3 = -1
puts(c3) # this is the way of functioning for an INTEGER...
c4 = ~0b1011 # 11 in binary is .. 1011.. '~' converts all 0's to one and vice versa..
puts(c4) # Thus we get.. 0100.. thats 4.. DOUBT... DO NOTE..?????????????????????????
c5 = 1 ^ 0
puts(c5)
#--------------------------------------------------------------------------------------------------------------------------------
# working of comparison operators
print("\nvalue of a1 is: #{a1} and value of a2 is: #{a2}\n")
s1 = a1<a2
puts(s1)
s2 = a1>a2
puts(s2)
s3 = a1<=a2
puts(s3)
s4 = a1>=a2
puts(s4)
s5 = a1<=>a2 # note the working of the comparison operator of Ruby it prints the value of 1 if a1>a2, 0 if both r equal and -1 if a1<a2
puts(s5) # the idea behind this operator is that it a multipurpose general operator.. hence.. used in classes.. it provides convenience..
#--------------------------------------------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment