Tuesday, February 18, 2014

Operators in Ruby - Part 1

Using Operators in Ruby - Part 1 - Source for the tutorial is Ruby Programming Language by Yukihiro Matsumoto(creator of Ruby) and David Flanagan.

The blog below has a sample code with output. The sample code below with inline comments in a way summarizes the concept(refer blog title) covered as part of the book.

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
view raw op1_output hosted with ❤ by GitHub
# 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..
#--------------------------------------------------------------------------------------------------------------------------------
view raw Operators1.rb hosted with ❤ by GitHub


No comments:

Post a Comment