Ruby Basics

                                               puts

[root@ruby ~]# irb
irb(main):001:0> 1+5
=> 6
irb(main):002:0> puts “hello world”
hello world
=> nil
irb(main):003:0> quit

========================================
[root@ruby ~]# cat >hello.rb
print(10+5)
print(“\n”)
puts “Hai how are you”
[root@ruby ~]# ruby hello.rb
15
Hai how are you
========================================
[root@ruby ~]# irb
irb(main):001:0> 5
=> 5
irb(main):002:0> 5*5
=> 25
irb(main):003:0> 4+7
=> 11
irb(main):004:0> quit
========================================
[root@ruby ~]# irb
irb(main):001:0> 1+3*5
=> 16
irb(main):002:0> “hello, world”
=> “hello, world”
irb(main):003:0> “hello,” + “world”
=> “hello,world”
irb(main):004:0> first=”hello”
=> “hello”
irb(main):005:0> first + “world”
=> “helloworld”
irb(main):006:0> quit
========================================
[root@ruby ~]# 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
irb(main):006:0>

[root@ruby ~]# 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
irb(main):006:0>
========================================
                                                 functions

[root@ruby ~]# irb
irb(main):001:0> def square(n)
irb(main):002:1> return n*n
irb(main):003:1> end
=> nil
irb(main):004:0> square 2
=> 4
irb(main):005:0> square 5
=> 25
irb(main):006:0> square (3)
=> 9
irb(main):007:0>
========================================

irb(main):007:0> def sum(num1,num2)
irb(main):008:1> num1+num2
irb(main):009:1> end
=> nil
irb(main):010:0> sum(6,8)
=> 14
irb(main):011:0> sum(10,25)
=> 35
irb(main):012:0>
========================================

getsirb(main):006:0> puts “now”,”is”,”time”,”to”,”enjoy”
now
is
time
to
enjoy
=> nil
irb(main):007:0> puts “hello!”,”how are you!”
hello!
how are you!
=> nil

========================================

                                                          gets

[root@ruby ~]# irb
irb(main):001:0>
irb(main):001:0> name = gets
mohammed
=> “mohammed\n”
irb(main):002:0> name
=> “mohammed\n”
irb(main):003:0> print(name)
mohammedInteger(num1) + Integer(num2)
=> nil
irb(main):004:0> print(name.chomp)
mohammed=> nil
irb(main):005:0>

==================================================

irb(main):005:0> num1 = gets
3
=> “3\n”
irb(main):006:0> num2 = gets
6
=> “6\n”
irb(main):007:0> num1 + num2
=> “3\n6\n”
irb(main):008:0> Integer(num1) + Integer(num2)
=> 9

==================================================

[root@ruby ~]# vim ex1.rb
print (“please enter your name:”)
name = gets
puts (“Hello, ” + name)
[root@ruby ~]# ruby ex1.rb
please enter your name:shaik
Hello, shaik
==================================================
[root@ruby ~]# vim ex2.rb
print (“enter the first num to add:”)
num1 = gets
print (“enter second num to add:”)
num2 = gets
result = Integer(num1) + Integer(num2)
print (result)

[root@ruby ~]# ruby ex2.rb
enter the first num to add:13
enter second num to add:16
29
==================================================
Data Types

[root@ruby ~]# irb
irb(main):001:0> name = ‘shaik’
=> “shaik”
irb(main):002:0> name = “shaik”
=> “shaik”
irb(main):003:0> name = gets
jack
=> “jack\n”
irb(main):004:0> print(name)
jack
=> nil
irb(main):005:0> name = “shaik\tmohammed”
=> “shaik\tmohammed”
irb(main):006:0> name = “shaik\smohammed”
=> “shaik mohammed”
irb(main):007:0> print name
shaik mohammed=> nil
irb(main):008:0> name = “shaik\tmohammed”
=> “shaik\tmohammed”
irb(main):009:0> print name
shaik mohammed=> nil
irb(main):010:0> str = “jack’s”
=> “jack’s”
irb(main):011:0> print str
jack’s=> nil
irb(main):012:0> str = ‘jack’s’
irb(main):013:0′ print str
irb(main):014:0′ ^C
irb(main):014:0> str = ‘jack\’s’
=> “jack’s”
irb(main):015:0> print str
jack’s=> nil
irb(main):016:0> exit
==================================================
Strings

[root@ruby ~]# vim one.rb
words = <<HERE
today is wednesday
we will bw having meating today.
HERE
print (words)

[root@ruby ~]# ruby one.rb
today is wednesday
we will bw having meating today.
==================================================
[root@ruby ~]# irb
irb(main):001:0> first,last = “shaik,mohammed”.split(/,/)
=> [“shaik”, “mohammed”]
irb(main):002:0> print first
shaik=> nil
irb(main):003:0> print last
mohammed=> nil
irb(main):004:0> first = “jack ”
=> “jack ”
irb(main):005:0> second = “jill”
=> “jill”
irb(main):006:0> print(first + second)
jack       jill=> nil
irb(main):007:0> print(first.squeeze + second)
jack jill=> nil
======================================================

 Numbers

[root@ruby ~]# irb
irb(main):001:0> 78
=> 78
irb(main):002:0> 34.5632123123
=> 34.5632123123
irb(main):003:0> 0b1010
=> 10
irb(main):004:0> 0x10
=> 16
irb(main):005:0> 0x1010
=> 4112
irb(main):006:0> 0x101
=> 257
irb(main):007:0> -234
=> -234
irb(main):008:0> 78+4
=> 82
irb(main):009:0> 5-2.4
=> 2.6
irb(main):010:0> 8-0.08
=> 7.92
irb(main):011:0> 12*12
=> 144
irb(main):012:0> 56/4
=> 14
irb(main):013:0> 25%5
=> 0
irb(main):014:0> 4**2
=> 16
irb(main):015:0> -54.abs
=> 54
irb(main):016:0> 12.div(2)
=> 6
irb(main):017:0> 12.modulo(5)
=> 2
irb(main):018:0> 110.to_s
=> “110”
===========================================
                                          Boolean
[root@ruby ~]# irb
irb(main):001:0> true
=> true
irb(main):002:0> false
=> false
irb(main):003:0> 100 > 1
=> true
irb(main):004:0> 1>100
=> false
irb(main):005:0> flag = true
=> true
irb(main):006:0> flag
=> true
irb(main):008:0> flag = false
=> false
irb(main):009:0> flag
=> false
irb(main):010:0> !flag
=> true
irb(main):012:0> !!flag
=> false
==========================================
                                                 Ranges

[root@ruby ~]# 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?(‘k’)
=> true
irb(main):007:0> letters.include?(‘1’)
=> false
irb(main):008:0> letters.min
=> “a”
irb(main):009:0> letters.max
=> “z”
irb(main):012: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”
irb(main):013:0> letters.each {|letter| puts(letter)}
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”
irb(main):014:0> letters.each {|letter| print(letter)}
abcdefghijklmnopqrstuvwxyz=> “a”..”z”
irb(main):015:0> letters === ‘c’
=> true
irb(main):016:0> digits = 0..9
=> 0..9
irb(main):017:0> digits === 100
=> false
irb(main):020:0> letters.include?(‘g’)
=> true
irb(main):021:0> digits.include?(‘7’)
=> false
irb(main):022:0> digits === 7
=> true
=====================================================

                                                Arrays

[root@ruby ~]# irb
irb(main):001:0> numbers =[1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
irb(main):002:0> names = [“tom”,”jack”,”david”]
=> [“tom”, “jack”, “david”]
irb(main):003:0> grades = [50,75,90]
=> [50, 75, 90]
irb(main):004:0> grades[0]
=> 50
irb(main):005:0> grades[3]
=> nil
irb(main):006:0> grades[2]
=> 90
irb(main):007:0> sum = grades[0]+grades[1]+grades[2]
=> 215
irb(main):008:0> digits = 0..9
=> 0..9
irb(main):009:0> nums =digits.to_a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):010:0> nums[4]
=> 4
===============================================

                                                 Hashes

[root@ruby ~]# irb
irb(main):001:0> numbers = {
irb(main):002:1* ‘james’ => ‘123’,
irb(main):003:1* ‘bond’ => ‘234’
irb(main):004:1> }
=> {“james”=>”123”, “bond”=>”234”}
irb(main):005:0> numbers[‘bond’]
=> “234”
irb(main):006:0> numbers[‘james’]
=> “123”
irb(main):007:0> numbers[‘mike’]
=> nil
==============================================

                       Creating Variables & constants

[root@ruby ~]# irb
irb(main):001:0> number = 111
=> 111
irb(main):002:0> number
=> 111
irb(main):003:0> _name = “simon”
=> “simon”
irb(main):004:0> name
NameError: undefined local variable or method `name’ for main:Object
from (irb):4
from /usr/bin/irb:12:in `’
irb(main):005:0> _name
=> “simon”
irb(main):006:0> first_name = “joe”
=> “joe”
irb(main):007:0> first_name
=> “joe”
irb(main):008:0> $salary = 1000
=> 1000
irb(main):009:0> salary
NameError: undefined local variable or method `salary’ for main:Object
from (irb):9
from /usr/bin/irb:12:in `’
irb(main):010:0> $salary
=> 1000
irb(main):011:0> PI = 3.14
=> 3.14
irb(main):012:0> PI
=> 3.14
irb(main):013:0> PI = 3.4
(irb):13: warning: already initialized constant PI
(irb):11: warning: previous definition of PI was here
=> 3.4
irb(main):014:0> PI
=> 3.4
==================================================

                                           To find min and max num in arrays

[root@ruby ~]# vim minmax.rb
nums = []
i = 0
while i < 10 nums[i] = Random.rand(101) 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@ruby ~]# ruby minmax.rb
[58, 51, 20, 12, 87, 46, 21, 6, 26, 41]
maximum value is :87

[root@ruby ~]# vim minmax.rb
nums = []
i = 0
while i < 10 nums[i] = Random.rand(101) 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] < min
min = nums[i]
end
end
puts(“Minimum value is :” +min.to_s)
[root@ruby ~]# ruby minmax.rb
[37, 69, 68, 91, 80, 94, 75, 41, 53, 5]
maximum value is :94
Minimum value is :5

[root@ruby ~]# ruby minmax.rb
[24, 61, 65, 50, 34, 43, 4, 38, 80, 69]
maximum value is :80
Minimum value is :4
===============================================

                                 Realtional operators

[root@ruby ~]# irb
irb(main):001:0> sal = 100
=> 100
irb(main):002:0> hours = 10
=> 10
irb(main):005:0> sal == 100 and hours == 10
=> true
irb(main):006:0> sal == 10 and hours == 10
=> false
irb(main):007:0> sal == 100 && hours == 5
=> false
irb(main):009:0> sal == 100 or hours == 1
=> true
irb(main):010:0> sal == 10 or hours == 10
=> true
irb(main):011:0> sal == 10 or hours == 1
=> false
irb(main):012:0> sal == 100 || hours == 10
=> true
irb(main):013:0> not true
=> false
irb(main):014:0> not false
=> true
irb(main):015:0> sal == 100
=> true
irb(main):016:0> not sal == 100
=> false
irb(main):017:0> !sal == 100
=> false

===============================================

[root@ruby ~]# irb
irb(main):001:0> a=b=c=0
=> 0
irb(main):002:0> a
=> 0
irb(main):003:0> b
=> 0
irb(main):004:0> c
=> 0
irb(main):005:0> defined? a
=> “local-variable”
irb(main):006:0> defined? d
=> nil
irb(main):007:0> defined? printf
=> “method”
irb(main):008:0> defined? d=1
=> “assignment”
irb(main):009:0> defined? d=>1
==================================
[root@ruby ~]# irb
irb(main):001:0> a = 10
=> 10
irb(main):002:0> b = 20
=> 20
irb(main):003:0> tmp = a
=> 10
irb(main):004:0> a = b
=> 20
irb(main):005:0> b = tmp
=> 10
irb(main):006:0> a
=> 20
irb(main):007:0> b
=> 10
irb(main):008:0> c = 30
=> 30
irb(main):009:0> d = 40
=> 40
irb(main):010:0> c,d = d,c
=> [40, 30]
irb(main):011:0> c
=> 40
irb(main):012:0> d
=> 30

=======================================

[root@ruby ~]# formulas.rb
#x / y-3
x = -13
y = 2.0
print(x / y-3)

[root@ruby ~]# ruby formulas.rb
-9.5

========================================

                                          simple if statement

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

[root@ruby ~]# ruby if.rb
55

=======================================
                                             if else

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

[root@ruby ~]# ruby ifelse.rb
please enter grade 90
pass
[root@ruby ~]# ruby ifelse.rb
please enter grade 50
fail
==============================================

if-elseif

[root@ruby ~]# cat ifelseif.rb
puts(“enter the grade:”)
grade = Integer(gets)
if grade >= 90
lettergrade = “A”
elsif grade >= 80
lettergrade = “B”
elsif grade >= 70
lettergrade = “C”
else
lettergrade = “fail”
end
puts(“the letter grade is ” + lettergrade)
[root@ruby ~]# ruby ifelseif.rb
enter the grade:
90
the letter grade is A
[root@ruby ~]# ruby ifelseif.rb
enter the grade:
70
the letter grade is C
[root@ruby ~]# ruby ifelseif.rb
enter the grade:
80
the letter grade is B
[root@ruby ~]# ruby ifelseif.rb
enter the grade:
59
the letter grade is fail
=====================================

                                       Case Statement

[root@ruby ~]# vim case.rb
print(“Enter a grade: “)
grade = Integer(gets)
case grade
when 90..100
lettergrade = “A”
when 80..90
lettergrade = “B”
when 70..89
lettergrade = “C”
when 60..70
lettergarde = “D”
else
lettergrade = “Fail”
end
print(“lettergrade” + lettergrade )
[root@ruby ~]# ruby case.rb
Enter a grade: 90
lettergradeA
[root@ruby ~]# ruby case.rb
Enter a grade: 80
lettergradeB
[root@ruby ~]# ruby case.rb
Enter a grade: 50
lettergradeFail
==================================

[root@ruby ~]# vim game.rb
answer = “cricket\n”
puts(“lets play a game.you get 3 tries”)
print(“what is the name of the game that sachin played ?”)
response = gets
if response == answer
puts (“thats correct”)
else
print (“sorry try again:”)
response = gets
if response == answer
puts (“thats correct”)
else
print (“sorry try again:”)
response = gets
if response == answer
puts (“thats correct”)
else
puts(“answer is criket”)
end
end
end
[root@ruby ~]# ruby game.rb
lets play a game.you get 3 tries
what is the name of the game that sachin played ?hockey
sorry try again:chess
sorry try again:golf
answer is criket
===============================

[root@ruby ~]# vim case1.rb
print(“enter the first number:”)
num1 = Integer(gets)
print(“enter the second number:”)
num2 = Integer(gets)
print (“enter a operation (+,-,*,/): “)
op = gets
op = op.chomp
case op
when “+”
puts(num1 + num2)
when “-”
puts(num1 – num2)
when “*”
puts(num1 * num2)
when “/”
puts(num1 / num2)
end
[root@ruby ~]# ruby case1.rb
enter the first number:9
enter the second number:9
enter a operation (+,-,*,/): +
18
[root@ruby ~]# ruby case1.rb
enter the first number:10
enter the second number:20
enter a operation (+,-,*,/): *
200
[root@ruby ~]# ruby case1.rb
enter the first number:9
enter the second number:3
enter a operation (+,-,*,/): /
3
[root@ruby ~]# ruby case1.rb
enter the first number:34
enter the second number:4
enter a operation (+,-,*,/): –
30
===========================================

                                                      While-loop

[root@ruby ~]# vim while.rb
count = 1
while (count <= 5)
puts (“Hello World”)
count += 1
end
[root@ruby ~]# ruby while.rb
Hello World
Hello World
Hello World
Hello World
Hello World

[root@ruby ~]# vim while1.rb
sum = 0
number = 1
while (number <= 10)
sum += number
number += 1
end
puts(sum)

[root@ruby ~]# ruby while1.rb
55
=========================================

                                              untill-loop

[root@ruby ~]# vim until.rb
count = 1
until (count > 5)
print (“Hello World\n”)
count += 1
end

[root@ruby ~]# ruby until.rb
Hello World
Hello World
Hello World
Hello World
Hello World

[root@ruby ~]# vim until1.rb
sum = 0
number = 1
until number > 10
sum += number
number += 1
end
puts(sum)

[root@ruby ~]# ruby until1.rb
55
===================================

                                                     Iterators loop

[root@ruby ~]# vim iterators.rb
5.times do
print “Hello world \n”
end

[root@ruby ~]# ruby iterators.rb
Hello world
Hello world
Hello world
Hello world
Hello world
================
root@ruby ~]# vim iterators1.rb
1.upto(10) do |x|
print x, ” ”
end

[root@ruby ~]# ruby iterators1.rb
1 2 3 4 5 6 7 8 9 10
================
[root@ruby ~]# vim iterators2.rb
sum = 0
1.upto(10) do |x|
sum += x
print sum, ” ”
end
[root@ruby ~]# ruby iterators2.rb
1 3 6 10 15 21 28 36 45 55
================
[root@ruby ~]# vim iterators3.rb
sum = 0
1.upto(10) do |x|
sum += x
end
print sum

[root@ruby ~]# ruby iterators3.rb
55
=====================================

[root@ruby ~]# vim even.rb
0.step(100,2) {|x| print x, ” “}

[root@ruby ~]# ruby even.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@ruby ~]# vim odd.rb
sum = 0
1.step(10,2) {|x| sum += x}
print sum
[root@ruby ~]# ruby odd.rb
25
==============================

                                            For-loop

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

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

[root@ruby ~]# vim ex.rb
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
for num in nums
sum += num
end
print sum

[root@ruby ~]# ruby ex.rb
55

=============================

                                                               Altering loop

[root@ruby ~]# vim pre.rb
cont = ‘y’
while (cont == ‘y’)
print(“enter a numerator:”)
num = Integer(gets)
print(“enter the denominator:”)
denom = Integer(gets)
puts (num/denom)
print(“More? (y/n) “)
cont = gets
cont = cont.chomp
end

[root@ruby ~]# ruby pre.rb
enter a numerator:10
enter the denominator:2
5
More? (y/n) y
enter a numerator:16
enter the denominator:4
4
More? (y/n) n

[root@ruby ~]# ruby pre.rb
enter a numerator:25
enter the denominator:0
pre.rb:7:in `/’: divided by 0 (ZeroDivisionError)
from pre.rb:7:in `<main>’
==================================

[root@ruby ~]# cat pre.rb
cont = ‘y’
while (cont == ‘y’)
print(“enter a numerator:”)
num = Integer(gets)
print(“enter the denominator:”)
denom = Integer(gets)
if denom == 0 then
next
end
puts (num/denom)
print(“More? (y/n) “)
cont = gets
cont = cont.chomp
end

[root@ruby ~]# ruby pre.rb
enter a numerator:25
enter the denominator:0
enter a numerator:36
enter the denominator:6
6
More? (y/n) n

========================================

Classes
———————————-
[root@ruby ~]# vim name.rb
class Rafi
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
end
aName = Rafi.new(“shaik”,”mohammed”,”rafi”)
print aName.inspect

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

———————————-
[root@ruby ~]# cat name.rb
class Rafi
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
def to_string
print(@first + ” ” + @middle + ” ” + @last)
end
end
aName = Rafi.new(“shaik”,”mohammed”,”rafi”)
print aName.to_string

[root@ruby ~]# ruby name.rb
shaik mohammed rafi
———————————-

[root@ruby ~]#vim name.rb
class Rafi
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_string
print(@first + ” ” + @middle + ” ” + @last)
end
end
aName = Rafi.new(“shaik”,”mohammed”,”rafi”)
print aName.to_string
print (“\n”)
print aName.first
[root@ruby ~]# ruby name.rb
shaik mohammed rafi
shaik
———————————-
[root@ruby ~]# vim name.rb
class Rafi
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_string
print(@first + ” ” + @middle + ” ” + @last)
end
end
aName = Rafi.new(“shaik”,”mohammed”,”rafi”)
print aName.to_string
print (“\n”)
print “first name :” + aName.first
print “\n”
print “middle name :” + aName.middle
print “\n”
print “last name :” + aName.last
[root@ruby ~]# ruby name.rb
shaik mohammed rafi
first name :shaik
middle name :mohammed
last name :rafi
——————————–

[root@ruby ~]# vim class.rb
class Example
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
attr_writer :first,:middle,:last
def to_string
print(@first + “,” + @middle + “,” + @last)
end
end
aName = Example.new(“Jane”,”victor”,”Brown”)
aName.first = “Jane”
aName.middle = “victor”
aName.last = “Brown”
print aName.to_string

[root@ruby ~]# ruby class.rb
Jane,victor,Brown

==================================================

[root@ruby ~]# vim class.rb
class Example
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
end
attr_reader :first,:middle,:last
attr_writer :first,:middle,:last
def to_string
print(@first + “,” + @middle + “,” + @last)
end
end
aName = Example.new(“Jane”,”victor”,”Brown”)
aName.first = “Jane”
aName.middle = “victor”
aName.last = “Brown”
print aName.first + ” ”
print aName.middle + ” ”
print aName.last

[root@ruby ~]# ruby class.rb
Jane victor Brown

==============================

                                       Class-Variables & class-methods

[root@ruby ~]# vim variable.rb
class Name
@@count = 0
def initialize(first,middle,last)
@first = first
@middle = middle
@last = last
@@count += 1
end
attr_reader :first, :middle, :last
attr_writer :first, :middle, :last
def to_string
print(@last + “, ” + @first + ” ” + @middle)
end
def self.count
return @@count
end
end
aName = Name.new(“shaik”,”mohammed”,”rafi”)
print Name.count
anotherName =Name.new(“syed”,”ali”,”khan”)
print “\n”
print Name.count
[root@ruby ~]# ruby variable.rb
1
2

=================================================

[root@ruby ~]# vim person.rb
class Person
def initialize(name,age,gender)
@name = name
@age = age
@gender = gender
end
def to_string
print(“name:”, @name, “\n”)
print(“age:”, @age, “\n”)
print(“gender:”, @gender, “\n”)
end
def birthday
@age += 1
end
end
p1 = Person.new(“shaik”,24,”M”)
p2 = Person.new(“mohammed”,25,”M”)
p3 = Person.new(“girl”,26,”F”)
p1.to_string
p2.to_string
p3.to_string
p3.birthday
p3.to_string
[root@ruby ~]# ruby person.rb
name:shaik
age:24
gender:M
name:mohammed
age:25
gender:M
name:girl
age:26
gender:F
name:girl
age:27
gender:F

==============================
[root@ruby ~]# 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@ruby ~]# ruby student.rb
Name: smith
Id: 123
[90, 80]
85
===============================
[root@ruby ~]# 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@ruby ~]# ruby shape.rb
x:10y:12
x:15y:14
===========================================

sub-class
[root@ruby ~]# vim subclass.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)
[root@ruby ~]# ruby subclass.rb
x:5y:10height: 3 width: 7

==========================================
                                          square

[root@ruby ~]# 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)
s1 = Square.new(7,12,4,4)
puts(s1.to_s)

[root@ruby ~]# ruby square.rb
x:5y:10height: 3 width: 7
square: x:7y:12height: 4 width: 4
====================================================

[root@ruby ~]# vim emp.rb
class Emp
def initialize(name,payrate)
@name = name
@payrate = payrate
end

def name
return @name
end

def pay(hours)
return @payrate * hours
end
end

class Manager < Emp
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 = Emp.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(“jack”,50,false)
print(m2.name,”pay:”,m2.pay(50))

[root@ruby ~]# ruby emp.rb
brownpay:800
smithpay:1200
jackpay:2500

=============================================

                                     Modules

[root@ruby ~]# vim Familiar.rb
module Familiar
def familiar.greeting
return “whats’s up”
end
end

[root@ruby ~]# vim Stranger.rb
module Stranger
def Stranger.greeting
return “how are you”
end
end

[root@ruby ~]# vim namespace.rb
require “./Familiar”
require “./Stranger”

print(Familiar.greeting)
print(“\n”)
print(Stranger.greeting)
==============================

                                                    Mixins

[root@ruby ~]# vim Constants.rb
module Constants
PI = 3.14
R = 2.7
GR = 1.6
end

[root@ruby ~]# vim Circle.rb
require “./Constants”
class Circle
include Constants

def initialize(radius)
@radius = radius
end

def getArea
return @radius * @radius * Constant::PI
end
end

circ = Circle.new(5)
print(circ.getArea)
===================================

[root@ruby ~]# vim math.rb
module Mathlist
def Mathlist.add(num1, *more)
sum = num1
for i in more
sum += i
end
return sum
end

def Mathlist.sub(num1, *more)
diff = num1
for i in more
diff -= i
end
return diff
end

def Mathlist.mul(num1, *more)
prod = num1
for i in more
prod *= i
end
return prod
end
end
[root@ruby ~]# vim usemath.rb
require “./Mathlist”

print(Mathlist.add(1,2,3))
print(“\n”)
print(Mathlist.sub(10,2,4,3))
print(“\n”)
print(Mathlist.mul(1,2,3,4,5))
=======================================
                                                   Reading files

[root@ruby ~]# vim file1
this is line 1
this is line 2
3
4
5
6

[root@ruby ~]# vim file2.rb
while line = gets
puts line
end

[root@ruby ~]# ruby file2.rb file1
this is line 1
this is line 2
3
4
5
6
==================

or

[root@ruby ~]# vim file2.rb
File.open(“file1”) do |file|
while line = file.gets
puts line
end
end

[root@ruby ~]# ruby file2.rb
this is line 1
this is line 2
3
4
5
6
========================================

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s