ruby basics

[root@node1 ~]# yum info ruby
Loaded plugins: fastestmirror
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
Loading mirror speeds from cached hostfile
* base: centos.excellmedia.net
* epel: epel.scopesky.iq
* extras: centos.excellmedia.net
* updates: centos.excellmedia.net
Available Packages
Name : ruby
Arch : x86_64
Version : 2.0.0.648
Release : 29.el7
Size : 68 k
Repo : base/7/x86_64
Summary : An interpreter of object-oriented scripting language
URL : http://ruby-lang.org/
License : (Ruby or BSD) and Public Domain
Description : Ruby is the interpreted scripting language for quick and easy
: object-oriented programming. It has many features to process text
: files and to do system management tasks (as in Perl). It is simple,
: straight-forward, and extensible.
[root@node1 ~]# yum install ruby -y

[root@node1 ~]# ruby –version
ruby 2.0.0p648 (2015-12-16) [x86_64-linux]

[root@node1 ~]# irb
irb(main):001:0> 1+2
=> 3
irb(main):002:0> puts “hello this is sample”
hello this is sample
=> nil
irb(main):003:0> exit
[root@node1 ~]#

[root@node1 ~]# vim one.rb
print(1+3)
print(“\n”)
puts”hello i am shaik”
[root@node1 ~]# ruby one.rb
4
hello i am shaik

[root@node1 ~]# irb
irb(main):001:0> 10
=> 10
irb(main):002:0> 10-7
=> 3
irb(main):003:0> 3*7
=> 21
irb(main):004:0> 9+3*7
=> 30
irb(main):005:0> “hai how are u”
=> “hai how are u”
irb(main):006:0> “hai,” + “how are u”
=> “hai,how are u”
irb(main):007:0> name = “shaik”
=> “shaik”
irb(main):008:0> name
=> “shaik”
irb(main):009:0> name + “mohammed”
=> “shaikmohammed”
——————————————–
[root@node1 ~]# irb
irb(main):001:0> i = 1
=> 1
irb(main):002:0> while i < 10
irb(main):003:1> print i
irb(main):004:1> i += 1
irb(main):005:1> end
123456789=> nil


Difference b/w puts and print functions

puts(“one”,”two”,”three”)
one
two
three
=> nil
——-
print(“Helo Bye”)
Helo Bye=> nil

print will be provide new line like puts
——
print(“Helo Bye\n”)
Helo Bye
=> nil
——

############### getting data in #############

[root@node1 ~]# irb
irb(main):001:0> name = gets
jack
=> “jack\n”
irb(main):002:0> name
=> “jack\n”
irb(main):003:0> print(name)
jack
=> nil
irb(main):004:0> puts name
jack
=> nil
irb(main):005:0> print(name.chomp)
jack=> nil
irb(main):006:0> num1 = gets
5
=> “5\n”
irb(main):007:0> num2 = gets
3
=> “3\n”
irb(main):008:0> num1 + num2
=> “5\n3\n”
irb(main):009:0> Integer(num1) + Integer(num2)
=> 8
irb(main):010:0> num1 = gets
1.7
=> “1.7\n”
irb(main):011:0> num2 = gets
5.4
=> “5.4\n”
irb(main):012:0> num1 + num2
=> “1.7\n5.4\n”
irb(main):013:0> Float(num1) + Float(num2)
=> 7.1000000000000005
irb(main):014:0>

###################  basic programs  ##############################

[root@node1 ~]# vim ex1.rb
print(“please enter your name:”)
name = gets
puts(“Hello,” + name)

[root@node1 ~]# ruby ex1.rb
please enter your name:jack
Hello,jack

[root@node1 ~]# vim ex1.rb
print(“enter a number to add:”)
num1 = gets
print(“enter the another num to add:”)
num2 = gets
result = Integer(num1) + Integer(num2)
print(“result of adding” + num1 + “plus” + num2 + “is:”, + result)
[root@node1 ~]# ruby ex1.rb
please enter your name:john
Hello,john
enter a number to add:100
enter the another num to add:8
result of adding100
plus8
is:108

[root@node1 ~]# vim ex1.rb
print(“please enter your name:”)
name = gets
puts(“Hello,” + name)
print(“enter a number to add:”)
num1 = gets
print(“enter the another num to add:”)
num2 = gets
result = Integer(num1) + Integer(num2)
print(“result of adding ” + num1.chomp + “plus ” + num2.chomp + “is: “, + result )

[root@node1 ~]# ruby ex1.rb
please enter your name:tom
Hello,tom
enter a number to add:12
enter the another num to add:45
result of adding 12plus 45is: 57

Data-Types

Strings
[root@node1 ~]# irb
irb(main):001:0> name = “tom”
=> “tom”
irb(main):002:0> name = ‘tom’
=> “tom”
irb(main):003:0> name = gets
tom
=> “tom\n”
irb(main):004:0> name = “tom\tjerry”
=> “tom\tjerry”
irb(main):005:0> print(name)
tom jerry=> nil
irb(main):006:0> name = “tom\sjerry”
=> “tom jerry”
irb(main):007:0> print(name)
tom jerry=> nil
irb(main):008:0>

[root@node1 ~]# vim here.rb
words = <<HERE
today is
monday
i need to go
to office
HERE
print(words)

[root@node1 ~]# ruby here.rb
today is
monday
i need to go
to office

irb(main):004:0> first = “shaik “
=> “shaik ”
irb(main):005:0> last = “mohammed”
=> “mohammed”
irb(main):006:0> print(first + last)
shaik mohammed=> nil
irb(main):007:0> print(first.squeeze + last)
shaik mohammed=> nil

Numbers
[root@node1 ~]# irb
irb(main):001:0> 100
=> 100
irb(main):002:0> 3.14
=> 3.14
irb(main):003:0> 0b1011
=> 11
irb(main):004:0> 0x10
=> 16
irb(main):005:0> 0x16
=> 22
irb(main):006:0> 1+4
=> 5
irb(main):007:0> 2.4-0.5
=> 1.9
irb(main):008:0> 12*12
=> 144
irb(main):009:0> 36/6
=> 6
irb(main):010:0> 36%6
=> 0
irb(main):011:0> 47%4
=> 3
irb(main):012:0> 2**6
=> 64
irb(main):013:0> -14
=> -14
irb(main):014:0> -23.abs
=> 23
irb(main):015:0> 12.div(2)
=> 6
irb(main):016:0> 36.modulo(7)
=> 1
irb(main):017:0> 50.to_s
=> “50”
Boolen Data
[root@node1 ~]# irb
irb(main):001:0> true
=> true
irb(main):002:0> false
=> false
irb(main):003:0> 1 > 100
=> false
irb(main):004:0> 999 > 100
=> true
irb(main):005:0> flag = true
=> true
irb(main):006:0> flag
=> true
irb(main):007:0> !flag
=> false
irb(main):008:0> one = false
=> false
irb(main):009:0> one
=> false
irb(main):010:0> !one
=> true
irb(main):011:0> !!one
=> false
Ranges
[root@node1 ~]# irb
irb(main):001:0> 0..9
=> 0..9
irb(main):002:0> ‘a’..’z’
=> “a”..”z”
irb(main):003:0> ‘aab’..’aae’
=> “aab”..”aae”
irb(main):004:0> letters = ‘a’..’z’
=> “a”..”z”
irb(main):005:0> letters
=> “a”..”z”
irb(main):006:0> letters.include?(‘r’)
=> true
irb(main):007:0> letters.include?(‘@’)
=> false
irb(main):008:0> letters.min
=> “a”
irb(main):009:0> letters.max
=> “z”
irb(main):011:0> letters.each {|letters| puts(letters)}
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
=> “a”..”z”
rb(main):014:0* letters.each {|letters| print(letters)}
abcdefghijklmnopqrstuvwxyz=> “a”..”z”
irb(main):015:0> digits = 0..9
=> 0..9
irb(main):016:0> digits === 100
=> false
irb(main):017:0> digits === 7
=> true
Arrays
[root@node1 ~]# irb
irb(main):001:0> numbers = [1,3,5,7,9,4]
=> [1, 3, 5, 7, 9, 4]
irb(main):002:0> names = [“jack”, “james”, “john”, “lin”]
=> [“jack”, “james”, “john”, “lin”]
irb(main):003:0> grades = [65, 75, 85]
=> [65, 75, 85]
irb(main):004:0> names[3]
=> “lin”
irb(main):005:0> grades[1]
=> 75
irb(main):006:0> names[2]
=> “john”
irb(main):007:0> sum = grades[0]+grades[1]+grades[2]
=> 225

Hashes

[root@node1 ~]# irb
irb(main):001:0> numbers = {
irb(main):002:1* ‘jack’ => ‘123’,
irb(main):003:1* ‘jones’ => ‘456’,
irb(main):004:1* ‘tom’ => ‘789’
irb(main):005:1> }
=> {“jack”=>”123”, “jones”=>”456”, “tom”=>”789”}
irb(main):006:0> numbers
=> {“jack”=>”123”, “jones”=>”456”, “tom”=>”789”}
irb(main):007:0> numbers[‘jones’]
=> “456”
Variables & Constants
[root@node1 ~]# irb
irb(main):001:0> number = 100
=> 100
irb(main):002:0> number
=> 100
irb(main):003:0> _name = “symon”
=> “symon”
irb(main):004:0> first_name = “shaik”
=> “shaik”
irb(main):005:0> lastname = “Joe”
=> “Joe”
irb(main):006:0> $salary = 5000
=> 5000
irb(main):007:0> salary
NameError: undefined local variable or method `salary’ for main:Object
from (irb):7
from /bin/irb:12:in `’
irb(main):008:0> $salary
=> 5000
irb(main):009:0> PI = 3.14159
=> 3.14159
irb(main):010:0> PI
=> 3.14159
irb(main):011:0> PI = 10.59
(irb):11: warning: already initialized constant PI
(irb):9: warning: previous definition of PI was here
=> 10.59

irb(main):012:0> PI
=> 10.59

[root@node1 ~]# vim thanks.rb
print(“what is the name of the gift giver? “)
name = gets
name = name.chomp
print(“what present did they give you? “)
present = gets
prrsent = present.chomp
print(“How old are you on your bithday? “)
age = Integer(gets)
print(“what is your name?” )
yourName = gets
yourName = yourName.chomp
puts
puts
puts(“Dear ” + name + “, “)
puts
puts(“Thank you for the ” + present + “.”)
puts(“I really like it.I can’t belive “)
puts(“that I am already ” + age.to_s + ” years old.”)
puts(“Being ” + age.to_s + “feels Just like ” + (age-1).to_s + “.”)
puts
puts(“sincerely, “)
puts
puts(yourName)
[root@node1 ~]# ruby thanks.rb
what is the name of the gift giver? john
what present did they give you? shirt
How old are you on your bithday? 20
what is your name?rafi
Dear john,

Thank you for the shirt
.
I really like it.I can’t belive
that I am already 20 years old.
Being 20feels Just like 19.

sincerely,

rafi
[root@node1 ~]#

#######################

[root@node1 ~]# vim minmax.rb
nums = []
i = 0
while i < 10
nums[i] = Random.rand(200)
i += 1
end
print(nums)
puts
max = nums[0]
for i in 1..9
if nums[i] > max
max = nums[i]
end
end
puts(“Maximum value is: ” + max.to_s)

[root@node1 ~]# ruby minmax.rb
[111, 87, 174, 6, 198, 115, 79, 139, 137, 15]
Maximum value is: 198

[root@node1 ~]# ruby minmax.rb
[19, 114, 86, 179, 127, 34, 143, 0, 115, 11]
Maximum value is: 179

[root@node1 ~]# vim minmax.rb
nums = []
i = 0
while i < 10
nums[i] = Random.rand(200)
i += 1
end
print(nums)
puts
max = nums[0]
for i in 1..9
if nums[i] > max
max = nums[i]
end
end
puts(“Maximum value is: ” + max.to_s)
min = nums[0]
for i in 1..9
if nums[i] < max
max = nums[i]
end
end
puts(“Minimum value is: ” + max.to_s)

[root@node1 ~]# ruby minmax.rb
[156, 80, 3, 158, 189, 68, 135, 31, 41, 194]
Maximum value is: 194
Minimum value is: 3

[root@node1 ~]# ruby minmax.rb
[174, 114, 30, 156, 115, 105, 22, 43, 51, 184]
Maximum value is: 184
Minimum value is: 22

################################################3

Relational Operators

irb(main):002:0> 1 == 1
=> true
irb(main):003:0> 1 == 10
=> false
irb(main):004:0> 1 > 2
=> false
irb(main):005:0> 2 < 4 => true
irb(main):006:0> 5 <= 8 => true
irb(main):007:0> 9 >= 15
=> false
irb(main):008:0> 9 <=> 9
=> 0
irb(main):009:0> 9 <=> 17
=> -1
irb(main):010:0> 25 <=> 17
=> 1
irb(main):012:0> “ant” == “apple”
=> false
irb(main):013:0> “apple” == “apple”
=> true
irb(main):014:0> “Apple” == “apple”
=> false
irb(main):015:0> “box” <=> “box”
=> 0
irb(main):016:0> “box” <=> “boz”
=> -1
irb(main):017:0> “box” <=> “bot”
=> 1irb(main):018:0> “apple” > “ball”
=> false
irb(main):019:0> “cat” > “ball”
=> true

Logical Operators

[root@node1 ~]# irb
irb(main):001:0> salary = 100
=> 100
irb(main):002:0> hours = 20
=> 20
irb(main):004:0> salary == 100 and hours == 20
=> true
irb(main):005:0> salary < 100 and hours == 20 => false
irb(main):006:0> salary == 100 and hours > 20
=> false
irb(main):008:0> salary == 100 and hours >= 20
=> true
irb(main):009:0> not true
=> false
irb(main):010:0> not false
=> true
irb(main):011:0> salary == 100 && hours > 20
=> false
irb(main):012:0> salary == 100 or hours > 20
=> true
irb(main):013:0> salary < 100 || hours > 20
=> false
irb(main):014:0> ! salary == 20
=> false

swap and  miscellaneous

[root@node1 ~]# irb
irb(main):001:0> a = 5
=> 5
irb(main):002:0> b = 6
=> 6
irb(main):003:0> c = 7
=> 7
irb(main):004:0> a
=> 5
irb(main):005:0> b
=> 6
irb(main):006:0> c
=> 7
irb(main):007:0> a = b = c =0
=> 0
irb(main):008:0> a
=> 0
irb(main):009:0> b
=> 0
irb(main):010:0> c
=> 0
irb(main):011:0> defined? a
=> “local-variable”
irb(main):012:0> defined? printf
=> “method”
irb(main):013:0> defined? d = 1111
=> “assignment”
irb(main):014:0> x = 200
=> 200
irb(main):015:0> y = 999
=> 999
irb(main):016:0> temp = x
=> 200
irb(main):017:0> x = y
=> 999
irb(main):018:0> y =temp
=> 200
irb(main):019:0> x
=> 999
irb(main):020:0> y
=> 200
irb(main):021:0> x ,y = y, x
=> [200, 999]
irb(main):022:0> x
=> 200
irb(main):023:0> y
=> 999

[root@node1 ~]# vim formulas.rb
x = -13
y = 2.0
print(x / y-3)
puts
print(1 / (x+y))
puts
print(Math.sqrt(x**6+y**5))
puts
print((x+y).abs)
puts

[root@node1 ~]# ruby formulas.rb
-9.5
-0.09090909090909091
2197.0072826461
11.0

##################### simple if  ##############################

[root@node1 ~]# vim if.rb
grade = gets
grade = Integer(grade)
if grade >= 70
puts(“pass”)
end

[root@node1 ~]# ruby if.rb
59
[root@node1 ~]# ruby if.rb
78
pass

[root@node1 ~]# vim ifelse.rb
grade = gets
grade = Integer(grade)
if grade >= 70
puts(“pass”)
else
puts(“fail”)
end

[root@node1 ~]# ruby ifelse.rb
67
fail
[root@node1 ~]# ruby ifelse.rb
87
pass

[root@node1 ~]# vim ifelseif.rb
puts(“enter a grade: “)
grade = Integer(gets)
if grade >= 90
lettergrade = “A”
elsif grade >= 80
lettergrade = “B”
elsif grade >= 70
lettergrade = “C”
elsif grade >= 60
lettergrade = “D”
end
puts(“the letter grade is ” + lettergrade)
[root@node1 ~]# ruby ifelseif.rb
enter a grade:
67
the letter grade is D
[root@node1 ~]# ruby ifelseif.rb
enter a grade:
78
the letter grade is C
[root@node1 ~]# ruby ifelseif.rb
enter a grade:
90
the letter grade is A
[root@node1 ~]# ruby ifelseif.rb
enter a grade:
85
the letter grade is B

########################### case ############################

[root@node1 ~]# vim case.rb
#case expression
# when expression1
# statements
#
# when expression2
# satements
#
# else
# statement
# end
print(“enter a grade:” )
grade = Integer(gets)
case grade
when 90..100
lettergrade = “A”
when 80..90
lettergrade = “B”
when 70..80
lettergrade = “C”
when 60..70
lettergrade = “D”
else
lettergrade = “F”
end
print(lettergrade)
puts

[root@node1 ~]# ruby case.rb
enter a grade:78
C
[root@node1 ~]# ruby case.rb
enter a grade:56
F
[root@node1 ~]# ruby case.rb
enter a grade:90
A

[root@node1 ~]# vim guess.rb
answer = “delhi\n”
puts(“lets play a quiz .you have 3 chances.”)
print(“what is the capital of india?”)
response = gets
if response == answer
puts(“that’s correct”)
else
print(“sorry guess again:”)
reponse = gets
if response == answer
puts(“that’s correct”)
else
print(“sorry guess again:”)
reponse = gets
if response == answer
puts(“that’s correct”)
else
puts(“sorry answer is delhi.”)
end
end
end

[root@node1 ~]# ruby guess.rb
lets play a quiz .you have 3 chances.
what is the capital of india?chennai
sorry guess again:hyderabad
sorry guess again:mumbai
sorry answer is delhi.

[root@node1 ~]# ruby guess.rb
lets play a quiz .you have 3 chances.
what is the capital of india?delhi
that’s correct

##############################################################

[root@node1 ~]# vim cal.rb
print(“enter the first number: “)
number1 = Integer(gets)
print(“enter the second number: “)
number2 = Integer(gets)
print(“enter an operation (+,-,*,/): “)
op = gets
op = op.chomp
case op
when “+”
puts(number1 + number2)
when “-“
puts(number1 – number2)
when “*”
puts(number1 * number2)
when “/”
puts(number1 / number2)
end
[root@node1 ~]# ruby cal.rb
enter the first number: 25
enter the second number: 5
enter an operation (+,-,*,/): +
30
[root@node1 ~]# ruby cal.rb
enter the first number: 36
enter the second number: 6
enter an operation (+,-,*,/): –
30
[root@node1 ~]# ruby cal.rb
enter the first number: 26
enter the second number: 10
enter an operation (+,-,*,/): /
2
[root@node1 ~]# ruby cal.rb
enter the first number: 56
enter the second number: 43
enter an operation (+,-,*,/): *
2408

########################### while #####################

[root@node1 ~]# vim while.rb
#while comparison
#statements
#end

count = 1
while count <= 5
puts (“Hello you”)
count += 1
end

[root@node1 ~]# ruby while.rb
Hello you
Hello you
Hello you
Hello you
Hello you

[root@node1 ~]# vim while.rb
#while comparison
#statements
#end
count = 1
while count <= 5
puts (“Hello you”)
count += 1
end

sum = 0
number = 1
while number <= 10
sum += number
number += 1
end
puts(sum)
[root@node1 ~]# ruby while.rb
Hello you
Hello you
Hello you
Hello you
Hello you
55

############################## untill loop #############################

[root@node1 ~]# vim untill.rb
#until comparison
#statements
#end
count = 1
until count > 5
puts(“Hello world”)
count += 1
end

[root@node1 ~]# ruby untill.rb
Hello world
Hello world
Hello world
Hello world
Hello world

[root@node1 ~]# vim untill.rb
#until comparison
#statements
#end
count = 1
until count > 5
puts(“Hello world”)
count += 1
end

sum = 0
number = 1
until number > 10
sum += number
number += 1
end

print(sum)
puts
[root@node1 ~]# ruby untill.rb
Hello world
Hello world
Hello world
Hello world
Hello world
55

##################################### iterators ##########################

[root@node1 ~]# vim iterators.rb
5.times do
print “Hello how are you \n”
end

[root@node1 ~]# ruby iterators.rb
Hello how are you
Hello how are you
Hello how are you
Hello how are you
Hello how are you

[root@node1 ~]# vim iterators.rb
5.times do
print “Hello how are you \n”
end
####
1.upto(10) do |x|
print x, ” “
end
puts

[root@node1 ~]# ruby iterators.rb
Hello how are you
Hello how are you
Hello how are you
Hello how are you
Hello how are you
1 2 3 4 5 6 7 8 9 10

[root@node1 ~]# vim iterators.rb
5.times do
print “Hello how are you \n”
end
####
1.upto(10) do |x|
print x, ” “
end
puts
#####
sum =0
1.upto(10) do |x|
sum += x
end
print sum
puts
[root@node1 ~]# ruby iterators.rb
Hello how are you
Hello how are you
Hello how are you
Hello how are you
Hello how are you
1 2 3 4 5 6 7 8 9 10
55

[root@node1 ~]# vim iterators.rb
0.step(100,2) {|x| print x, ” “}
[root@node1 ~]# ruby iterators.rb
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

[root@node1 ~]# vim iterators.rb
sum = 0
1.step(10,2) {|x| sum += x}
print sum

[root@node1 ~]# ruby iterators.rb
25

[root@node1 ~]# vim each.rb
nums = [1,2,3,4,5]
nums.each do |x|
print x, “\n”
end

[root@node1 ~]# ruby each.rb
1
2
3
4
5

[root@node1 ~]# vim for.rb
nums = [1,2,3,4,5]
for num in nums
print num, “\n”
end

[root@node1 ~]# ruby for.rb
1
2
3
4
5

[root@node1 ~]# vim for.rb
nums = [1,2,3,4,5]
sum = 0
for num in nums
sum += num
end
print sum
puts

[root@node1 ~]# ruby for.rb
15

############################## Methods  #######################

[root@node1 ~]# vim methosp1.rb
def square(num)
num * num
end

number =2
numbersq = square(number)
print(numbersq)
puts

[root@node1 ~]# ruby methosp1.rb
4

[root@node1 ~]# vim methosp1.rb
def square(num)
num * num
end

def power(base,exp)
product = 1
while exp > 0
product *= base
exp -= 1
end
return product
end

number =2
numbersq = square(number)
print(numbersq, “\n”)
print(power(numbersq, 3))

[root@node1 ~]# ruby methosp1.rb
4
64

[root@node1 ~]# vim methosp2.rb
def prompt(message)
print message
end

def curve(arr,points)
arr.map! {|grade| grade += points}
end

grades = [60,70,80,90]
curve(grades,5)
grades.each {|grade| print grade, ” “}
[root@node1 ~]# ruby methosp2.rb
65 75 85 95

[root@node1 ~]# vim functions.rb
def sum(*args)
total = 0
for i in args
total += i
end
return total
end

print sum(1,2)
print(“\n”)
print sum(1,2,3,4,5,6,7,8)
[root@node1 ~]# ruby functions.rb
3
36

[root@node1 ~]# vim functions1.rb
def growth(principal,years,rate=1.01)
while years > 0
principal *= rate
years -= 1
end
return principal
end
print growth(1000,10,1.02)
print(“\n”)
print growth(1000,10)

[root@node1 ~]# ruby functions1.rb
1218.9944199947574
1104.6221254112045

[root@node1 ~]# vim tipcal.rb
def tipcal(amount)
return amount * 0.15
end

print(“enter the amount of the bill: “)
bill = Float(gets)
tip =tipcal(bill)
total = bill + tip
puts(“your total is” + total.to_s)
[root@node1 ~]# ruby tipcal.rb
enter the amount of the bill: 1450
your total is1667.5

################################################################

[root@node1 ~]# vim calmethod.rb
def add(n1,n2)
return n1 + n2
end

def sub(n1,n2)
return n1 – n2
end

def mul(n1,n2)
return n1 * n2
end

def div(n1,n2)
return n1 / n2
end

print(“enter the first number: “)
num1 = Integer(gets)
print(“enter the second number: “)
num2 = Integer(gets)
print(“enter an operation (+,-,*,/): “)
op = gets
op = op.chomp
if op == “+”
puts(add(num1,num2))
elsif op == “-“
puts(sub(num1,num2))
elsif op == “*”
puts(mul(num1,num2))
elsif op == “/”
puts(div(num1,num2))

else
puts(“Bad operation”)
end

[root@node1 ~]# ruby calmethod.rb
enter the first number: 56
enter the second number: 34
enter an operation (+,-,*,/): *
1904

#################### classses ###################################

[root@node1 ~]# vim class1.rb
class Name
def initialize(first,middle,last)  #### initialize method with parameters
@first = first   ###  members or fields of class
@middle = middle  ###assign those parameters to instance variables
@last = last
end
end

aName = Name.new(“shaik”,”mohammed”,”rafi”)   ###### Name-object
print aName.inspect
puts

[root@node1 ~]# ruby class1.rb
#<Name:0x00000001a65b48 @first=”shaik”, @middle=”mohammed”, @last=”rafi”>

[root@node1 ~]# vim class2.rb
class Name
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
def to_s  ###define to_s method
print(@first + ” ” + @middle + ” ” + @last)
end
end

aName = Name.new(“shaik”,”mohammed”,”rafi”)
print aName.to_s
puts

[root@node1 ~]# ruby class2.rb
shaik mohammed rafi

[root@node1 ~]# vim class3.rb
class Name
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
def first
@first
end
def middle
@middle
end
def last
@last
end
def to_s
print(@first + ” ” + @middle + ” ” + @last)
end
end
aName = Name.new(“shaik”,”mohammed”,”rafi”)
print aName.to_s
puts
print aName.first
puts
print aName.last
puts
print aName.middle
puts

[root@node1 ~]# ruby class3.rb
shaik mohammed rafi
shaik
rafi
mohammed

[root@node1 ~]# vim class4.rb
class Name
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
def first=(new_first)
@first = new_first
end
def to_s
print(@first + ” ” + @middle + ” ” + @last)
end
end
aName = Name.new(“shaik”,”mohammed”,”rafi”)
aName.first = “john”
print aName.to_s
puts

[root@node1 ~]# ruby class4.rb
john mohammed rafi

[root@node1 ~]# vim class5.rb
class Name
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
attr_writer :first, :middle, :last
def to_s
print(@first + ” ” + @middle + ” ” + @last)
end
end
aName = Name.new(“shaik”,”mohammed”,”rafi”)
aName.first = “john”
aName.middle = “lin”
aName.last = “moore”
print aName.to_s
puts
[root@node1 ~]# ruby class5.rb
john lin moore

[root@node1 ~]# vim class6.rb
class Name
@@count = 0      #declaring a variable
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
@@count += 1
end
attr_writer :first, :middle, :last
attr_reader :first, :middle, :last
def to_s
print(@first + ” ” + @middle + ” ” + @last)
end
def self.count
return @@count
end
end
aName = Name.new(“john”,”tom”,”cruze”)
print Name.count
anotherName = Name.new(“james”,”joosling”,”author”)
puts
print Name.count
[root@node1 ~]# ruby class6.rb
1
2

#####################################

[root@node1 ~]# vim person.rb
class Person
def initialize(name,age,gender)
@name = name
@age = age
@gender = gender
end

def to_s
print(“Name: “, @name, “\n”)
print(“Age: “, @age, “\n”)
print(“Gender: “, @gender, “\n”)
end
def birthday
@age += 1
end
end
p1 = Person.new(“jani”, 33, “m”)
p2 = Person.new(“tom”, 45, “f”)
p3 = Person.new(“jack”, 99, “m”)
p1.to_s
p2.to_s
p3.to_s
p3.birthday()
p3.to_s

[root@node1 ~]# ruby person.rb
Name: jani
Age: 33
Gender: m
Name: tom
Age: 45
Gender: f
Name: jack
Age: 99
Gender: m
Name: jack
Age: 100
Gender: m
[root@node1 ~]# vim student.rb
class Student
def initialize(name,id)
@name = name
@id = id
@grades = []
end

def to_s
puts(“Name: ” + @name)
puts(“Id: ” + @id)
print(@grades)
end

def addgrade(grade)
@grades.push(grade)
end

def gradeAVG
total = 0
for grade in @grades
total += grade
end
return total/@grades.count
end
end

s1 = Student.new(“smith”, “123”)
s1.addgrade(90)
s1.addgrade(80)
puts s1.to_s
print(s1.gradeAVG)

[root@node1 ~]# ruby student.rb
Name: smith
Id: 123
[90, 80]
85

[root@node1 ~]# vim shape.rb
class Shape
def initialize(x,y)
@x = x
@y = y
end
attr_reader :x, :y
attr_writer :x, :y

def to_s
print(“x: ” , x,”y: “, y)
end

def move(x,y)
@x += x
@y += y
end
end

s1 = Shape.new(10,12)
puts(s1.to_s)
s1.move(5,2)
puts(s1.to_s)
[root@node1 ~]# ruby shape.rb
x: 10y: 12
x: 15y: 14

################## inheritance ####################

[root@node1 ~]# vim rectangle.rb
class Shape
def initialize(x,y)
@x = x
@y = y
end
attr_reader :x, :y
attr_writer :x, :y

def to_s
print(“x: ” , x,”y: “, y)
end

def move(x,y)
@x += x
@y += y
end
end

class Rectangle < Shape
def initialize(x,y,w,h)
super(x,y)
@width = w
@height = h
end
end
r1 = Rectangle.new(5,10,7,3)
puts(r1.to_s)
[root@node1 ~]# ruby rectangle.rb
x: 5y: 10

———————————
[root@node1 ~]# vim rectangle1.rb
class Shape
def initialize(x,y)
@x = x
@y = y
end
attr_reader :x, :y
attr_writer :x, :y

def to_s
print(“x: ” , x,”y: “, y)
end

def move(x,y)
@x += x
@y += y
end
end

class Rectangle < Shape
def initialize(x,y,w,h)
super(x,y)
@width = w
@height = h
end
def to_s
print(super)
print(” height: “, @height.to_s + ” width: “, @width.to_s)
end
end
r1 = Rectangle.new(5,10,7,3)
puts(r1.to_s)
r2 = Rectangle.new(1,2,2,4);
puts(r2.to_s)

[root@node1 ~]# ruby rectangle1.rb
x: 1y: 2 height: 4 width: 2

[root@node1 ~]# vim square.rb
class Shape
def initialize(x,y)
@x = x
@y = y
end
attr_reader :x, :y
attr_writer :x, :y

def to_s
print(“x: ” , x,”y: “, y)
end

def move(x,y)
@x += x
@y += y
end
end

class Rectangle < Shape
def initialize(x,y,w,h)
super(x,y)
@width = w
@height = h
end
def to_s
print(super)
print(” height: “, @height.to_s + ” width: “, @width.to_s)
end
end

class Square < Rectangle
def initialize(x,y,w,h)
if w != h
w = h
end
super(x,y,w,h)
end
def to_s
print(“square: “)
print(super)
end
end
r1 = Rectangle.new(5,10,7,3)
puts(r1.to_s)
r2 = Rectangle.new(1,2,2,4);
puts(r2.to_s)
s1 = Square.new(7,12,5,5);
puts(s1.to_s)
[root@node1 ~]# ruby square.rb
x: 5y: 10 height: 3 width: 7
x: 1y: 2 height: 4 width: 2
square: x: 7y: 12 height: 5 width: 5

[root@node1 ~]# vim employee.rb
class Employee
def initialize(name,payrate)
@name = name
@payrate = payrate
end

def name
return @name
end

def pay(hours)
return @payrate * hours
end
end
class Manager < Employee
def initialize(name, payrate, salaried)
super(name, payrate)
@salaried = salaried
end

def pay(hours)
if @salaried
return @payrate
else
return @payrate * hours
end
end
end

e1 = Employee.new(“brown”, 20)
print(e1.name, “pay: “, e1.pay(40), “\n”)
m1 = Manager.new(“smith”, 1200 ,true)
print(m1.name, “pay: “, m1.pay(0), “\n”)
m2 = Manager.new(“jones”, 40 , false)
print(m2.name, “pay: “, m2.pay(80), “\n”)
[root@node1 ~]# ruby employee.rb
brownpay: 800
smithpay: 1200
jonespay: 3200

################# modules ##################

[root@node1 ~]# vim temperature.rb
def ctof(temp)
return temp * (9.0/5.0) + 32.0
end

def ftoc(temp)
return (temp – 32.0) * (5.0/9.0)
end

[root@node1 ~]# vim temp.rb
require ‘./temperature’

puts(ftoc(212))
puts(ctof(0))
[root@node1 ~]# ruby temp.rb
100.0
32.0

################

[root@node1 ~]# vim familiar.rb
module Familiar
def Familiar.greeting
return “what’s up?”
end
end
[root@node1 ~]# vim stranger.rb
module Stranger
def Stranger.greeting
return “How are you?”
end
end

[root@node1 ~]# vim namespace.rb
require “./familiar”
require “./stranger”

print(Familiar.greeting)
print(“\n”)
print(Stranger.greeting)
[root@node1 ~]# ruby namespace.rb
what’s up?
How are you?

#################      Exception Handling #########################

[root@node1 ~]# vim divbyzero.rb
print(“enter numerator: “)
num = Integer(gets)
print(“Enter denominator: “)
denom = Integer(gets)
ratio = num / denom
print(ratio)
[root@node1 ~]# ruby divbyzero.rb
enter numerator: 56
Enter denominator: 0
divbyzero.rb:5:in `/’: divided by 0 (ZeroDivisionError)
from divbyzero.rb:5:in `<main>’

[root@node1 ~]# ruby divbyzero.rb
enter numerator: 36
Enter denominator: 6
6
[root@node1 ~]# vim divbyzero.rb
begin
print(“enter numerator: “)
num = Integer(gets)
print(“Enter denominator: “)
denom = Integer(gets)
ratio = num / denom
print(ratio)
rescue
print $!
puts
print(“enter a denominator other than 0: “)
denom = Integer(gets)
ratio = num / denom
print(ratio)
end
[root@node1 ~]# ruby divbyzero.rb
enter numerator: 45
Enter denominator: 0
divided by 0
enter a denominator other than 0: 16
2

[root@node1 ~]# vim data.txt
this is line 1
this is second
third
1
2
3
4

[root@node1 ~]# vim readfile.rb
while line = gets
puts line
end
[root@node1 ~]# ruby readfile.rb data.txt
this is line 1
this is second
third
1
2
3
4

[root@node1 ~]# vim readfile.rb
File.open(“data.txt”) do |file|
while line = file.gets
puts line
end
end

[root@node1 ~]# ruby readfile.rb
this is line 1
this is second
third
1
2
3
4

Leave a comment