SlideShare ist ein Scribd-Unternehmen logo
1 von 27
RUBYRUBY
Ruby Classes and Objects
● Defining a Class:
class Example
end
● Creating Objects:
ex1=Example.new
ex2=Example.new
● Example:
● class Customer
@@no_of_customers=0
● def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
● end
● end
Example for Class and Object
● We declare the initialize method with id, name, and addr
as local variables.
● In the initialize method, we pass on the values of these
local variables to the instance variables @cust_id,
@cust_name, and @cust_addr.
● Now, we can create objects:
cust1=Customer.new("1", "Alex", "Coimbatore, TN")
cust2=Customer.new("2", "Balu", "Chennai, TN")
Member Functions in Ruby Class
● In Ruby, functions are called methods. Each method in a class starts with the
keyword def followed by the method name and end with the keyword end.
● Example:
● class Sample
def hello
puts "Hello Ruby!"
end
● end
object = Sample. new
object.hello //=> Hello Ruby!
Example for Class and Odject
● class Customer
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
● end
cust1=Customer.new("1", "Alex", "Coimbatore, TN")
cust2=Customer.new("2", "Balu", "Chennai, TN")
cust1.display_details()
cust1.total_no_of_customers()
cust2.display_details()
cust2.total_no_of_customers()
● Output:
Customer id 1
Customer name Alex
Customer address Coimbatore,TN
Customer id 2
Customer name Balu
Customer address Chennai,TN
Class Inheritance
● Inheritance From Base Class:
● class Parent
def implicit()
puts "Hello Parent"
end
● end
● class Child < Parent
● end
dad = Parent.new()
son = Child.new()
dad.implicit()
son.implicit()
● Output:
Hello Parent
Hello Parent
Inheritance Example
● class Parent
def override()
puts "Hi Parent"
end
● end
● class Child < Parent
def override()
puts "Hi Child"
end
● end
dad = Parent.new()
son = Child.new()
dad.override()
son.override()
● Output:
Hi Parent
Hi Child
Ruby Variables
● Ruby Global Variables:
Global variables begin with $.
● Example: $global_variable=100
● Ruby Instance Variables:
Instance variables begin with @.
● Example: @instance_variable=200
● Ruby Class Variables:
Class variables begin with @@ and must be initialized before they can
be used in method definitions.
● Example: @@class_variable=300
Ruby Arrays
● Creating an Array:
a=[1,2,3,4,5] ( or)
● ary=Array.new
ary[0]=1
ary[1]=2
ary[2]=3
● arr = ['a', 'b', 'c', 'd', 'e', 'f']
Accessing Array
● Accessing Element:
arr = [1, 2, 3, 4, 5, 6]
● arr[2] # 3
● arr[100] # nil
● arr[-3] # 4
● arr[2, 3] #[3, 4, 5]
● arr[1..4] #[2, 3, 4, 5]
● arr.take(3) # [1, 2, 3]
● arr.drop(3) # [4, 5, 6]
● arr.at(0) # 1
● arr.first # 1
● arr.last # 6
Adding Items to Arrays
● For adding can use either push or <<
● arr = [1, 2, 3, 4]
● arr.push(5) #[1, 2, 3, 4, 5]
● Arr << 6 #[1, 2, 3, 4, 5, 6]
● Add a new item to the beginning of an array:
● arr.unshift(0) # [0, 1, 2, 3, 4, 5, 6]
● Add a new element to an array at any position:
● arr.insert(3, 'apple') #[0, 1, 2, 'apple', 3, 4, 5, 6]
● arr.insert(3, 'orange', 'pear', 'grapefruit')
#[0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
Removing Items from an Array
● arr = [1, 2, 3, 4, 5, 6]
● arr.pop # 6
● arr # [1, 2, 3, 4, 5]
● arr.shift # 1
● arr # [2, 3, 4, 5]
● To delete an element at a particular index:
● arr.delete_at(2) # 4
● Arr # [2, 3, 5]
● To delete a particular element anywhere in an array:
● arr = [1, 2, 2, 3]
● arr.delete(2) # 2
● arr # [1,3]
Iteration in Array
● Ruby each:
● ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
● Ruby collect:
● a = [1,2,3,4,5]
b = a.collect { |x| 10*x }
puts b
● O/P:
● 1
2
3
4
5
● O/P:
● 10
20
30
40
50
Iteration in Array
● Ruby map:
● arr.map { |a| 2*a } # [2, 4, 6, 8, 10]
● arr # [1, 2, 3, 4, 5]
● arr.map! { |a| a**2 } # [1, 4, 9, 16, 25]
● arr # [1, 4, 9, 16, 25]
.each with index in Array
● a=[1,2,3,4,5]
a.each_with_index do |value, index|
puts "#{index} index value is #{value}!"
end
● Output:
0 index value is 1!
1 index value is 2!
2 index value is 3!
3 index value is 4!
4 index value is 5!
Iteration in Array
● Selecting Element:
● arr = [1, 2, 3, 4, 5, 6]
● arr.select { |a| a > 3 } #[4, 5, 6]
● arr.reject { |a| a < 3 } #[3, 4, 5, 6]
● Delete Element:
● arr.delete_if { |a| a < 4 } # [4, 5, 6]
● Arr # [4, 5, 6]
Operations in Array
● Remove Array:
● a = [ "a", "b", "c", "d", "e" ]
a.clear # [ ]
● Count:
● ary = [1, 2, 4, 2]
ary.count # 4
● Delete:
● a = [ "a", "b", "b", "b", "c" ]
a.delete("b") # "b"
a # ["a", "c"]
● Delete_at:
● a = ["ant", "bat", "cat", "dog"]
a.delete_at(2) # "cat"
a #["ant", "bat", "dog"]
● Drop:
● a = [1, 2, 3, 4, 5, 0]
a.drop(3) # [4, 5, 0]
● Join:
● [ "a", "b", "c" ].join # "abc"
● [ "a", "b", "c" ].join("-") # "a-b-c"
Ruby Hashes
●
Hashes are similar to arrays. Here we
can create a values and keys.
● Creating Hash:
● grade = { "Alex" => 10, "Balu" => 6 }
●
grade=Hash["a", 100, "b", 200]
●
grade=Hash["a" => 100, "b" => 200]
● h = Hash.new()
h["a"] = 100
h["b"] = 200
h #{"a"=>100, "b"=>200}
● Accessing Hash:
● h = { "a" => 100, "b" => 200 }
h[“a”] # 100
h[“c”] # nil
h[“b”] #200
.each in Hash
●
h = { "a" => 100, "b" => 200 }
h.each { |key, value| puts "#{key} is
#{value}" }
●
Output:
a is 100
b is 200
● h = { "a" => 100, "b" => 200 }
h.each_key {|key| puts key }
● Output:
a
b
● h = { "a" => 100, "b" => 200 }
h.each_value {|value| puts
value }
● Output:
100
200
● h.has_key?("a") #true
● h.has_key?("z") #false
● h.has_value?(100) # true
● h.has_value?(999) # false
Ruby if,Else if Stmt
● Ruby If:
● if var == 10
print “Variable is 10″
end
● Ruby Else If:
● x=5
if x > 2
puts "x is greater than 2"
elsif x <= 2
puts "x is #{x}"
else
puts "I can't guess the number"
end # x is greater than 2
● Unless stmt:
● x=5
unless x>2
puts "x is less than 2"
else
puts "x is greater than 2"
end
● #x is greater than 2
Hash Example with argument
● def hash_arg(opt={})
alpha={
:a=>'Apple',
:b=>'Banana',
:c=>'Carrot',
:d=>'Dog'
}.merge(opt)
puts "#{alpha[:a]} #{alpha[:b]} #{alpha[:c]}
#{alpha[:d]}"
puts opt
puts alpha
● end
hash_arg()
hash_arg(:e => 'and')
● Output:
● Apple Banana Carrot Dog
● {}
● {:a=>"Apple", :b=>"Banana",
:c=>"Carrot", :d=>"Dog"}
● Apple Banana Carrot Dog
● {:e=>"and"}
● {:a=>"Apple", :b=>"Banana",
:c=>"Carrot", :d=>"Dog", :e=>"and"}
Case Statement
● Case Stmt:
age = 5
case age
● when 0..2
puts "baby"
when 3..6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end
● Output:
little child
While and For loop
● While Loop:
● i = 0
while i < 5 do
puts "Inside the loop i = #{i}"
i +=1
end
● Output:
Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
● For Loop:
● array=[0,1,2,3,4,5]
● for i in array
puts "Value of i is #{i}"
end
● Output:
Value of local variable is 0
Value of local variable is 1
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
Methods in Ruby
● Defining a Method with default argument:
● def test(a1="Ruby", a2="Java")
puts "The programming language is #{a1}"
puts "The programming language is #{a2}"
● end
test "C", "C++"
test
● Output:
The programming language is C
The programming language is C++
The programming language is Ruby
The programming language is Java
● Defining a Method with Multiple argument:
● def some_method(a,b,*c,d)
puts "A contain #{a}"
puts "B contain #{b}"
puts "c contain #{c}"
puts "D contain #{d}"
● end
some_method(5,4,2,1,6,7,8,9,3)
● Output
A contain 5
B contain 4
c contain [2, 1, 6, 7, 8, 9]
D contain 3
Ruby Blocks
●
Example:
●
def test
puts "You are in the method"
yield
puts "You are again back to the
method"
yield
● end
test {
puts "You are in the block"
}
● Output:
You are in the method
You are in the block
You are again back to the
method
You are in the block
Ruby Blocks in Class Example:
● class Own_class < Array
● def double_each
self.each do |element|
yield(element*2)
end
● end
● end
d=Own_class.new([10, 20,
30, 40, 50])
d.double_each { |x|
puts x
}
● Output:
20
40
60
80
100
THANK YOUTHANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212Mahmoud Samir Fayed
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentationMartin McBride
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeManoj Kumar
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...Ontico
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeLuka Jacobowitz
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)진성 오
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
 
The Ring programming language version 1.5.3 book - Part 30 of 184
The Ring programming language version 1.5.3 book - Part 30 of 184The Ring programming language version 1.5.3 book - Part 30 of 184
The Ring programming language version 1.5.3 book - Part 30 of 184Mahmoud Samir Fayed
 
Perceptron
PerceptronPerceptron
Perceptronunhas
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FPLuka Jacobowitz
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Philip Schwarz
 
The Ring programming language version 1.5.4 book - Part 27 of 185
The Ring programming language version 1.5.4 book - Part 27 of 185The Ring programming language version 1.5.4 book - Part 27 of 185
The Ring programming language version 1.5.4 book - Part 27 of 185Mahmoud Samir Fayed
 

Was ist angesagt? (20)

Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Arrays matrix 2020 ab
Arrays matrix 2020 abArrays matrix 2020 ab
Arrays matrix 2020 ab
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
The Ring programming language version 1.5.3 book - Part 30 of 184
The Ring programming language version 1.5.3 book - Part 30 of 184The Ring programming language version 1.5.3 book - Part 30 of 184
The Ring programming language version 1.5.3 book - Part 30 of 184
 
Ds program-print
Ds program-printDs program-print
Ds program-print
 
Perceptron
PerceptronPerceptron
Perceptron
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
The Ring programming language version 1.5.4 book - Part 27 of 185
The Ring programming language version 1.5.4 book - Part 27 of 185The Ring programming language version 1.5.4 book - Part 27 of 185
The Ring programming language version 1.5.4 book - Part 27 of 185
 

Ähnlich wie Ruby Classes and Objects Explained

Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingThaichor Seng
 
Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014alex_perry
 
Rubyconfindia2018 - GPU accelerated libraries for Ruby
Rubyconfindia2018 - GPU accelerated libraries for RubyRubyconfindia2018 - GPU accelerated libraries for Ruby
Rubyconfindia2018 - GPU accelerated libraries for RubyPrasun Anand
 
Ruby on rails tips
Ruby  on rails tipsRuby  on rails tips
Ruby on rails tipsBinBin He
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )Victor Verhaagen
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyVysakh Sreenivasan
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
Buku kecil coffee script
Buku kecil coffee scriptBuku kecil coffee script
Buku kecil coffee scriptWidoyo PH
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 

Ähnlich wie Ruby Classes and Objects Explained (20)

Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Lua Study Share
Lua Study ShareLua Study Share
Lua Study Share
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014
 
Rubyconfindia2018 - GPU accelerated libraries for Ruby
Rubyconfindia2018 - GPU accelerated libraries for RubyRubyconfindia2018 - GPU accelerated libraries for Ruby
Rubyconfindia2018 - GPU accelerated libraries for Ruby
 
Web futures
Web futuresWeb futures
Web futures
 
Ruby on rails tips
Ruby  on rails tipsRuby  on rails tips
Ruby on rails tips
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Buku kecil coffee script
Buku kecil coffee scriptBuku kecil coffee script
Buku kecil coffee script
 
TRICK
TRICKTRICK
TRICK
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 

Kürzlich hochgeladen

USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 

Kürzlich hochgeladen (20)

Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 

Ruby Classes and Objects Explained

  • 2. Ruby Classes and Objects ● Defining a Class: class Example end ● Creating Objects: ex1=Example.new ex2=Example.new ● Example: ● class Customer @@no_of_customers=0 ● def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr ● end ● end
  • 3. Example for Class and Object ● We declare the initialize method with id, name, and addr as local variables. ● In the initialize method, we pass on the values of these local variables to the instance variables @cust_id, @cust_name, and @cust_addr. ● Now, we can create objects: cust1=Customer.new("1", "Alex", "Coimbatore, TN") cust2=Customer.new("2", "Balu", "Chennai, TN")
  • 4. Member Functions in Ruby Class ● In Ruby, functions are called methods. Each method in a class starts with the keyword def followed by the method name and end with the keyword end. ● Example: ● class Sample def hello puts "Hello Ruby!" end ● end object = Sample. new object.hello //=> Hello Ruby!
  • 5. Example for Class and Odject ● class Customer def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end ● end cust1=Customer.new("1", "Alex", "Coimbatore, TN") cust2=Customer.new("2", "Balu", "Chennai, TN") cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers() ● Output: Customer id 1 Customer name Alex Customer address Coimbatore,TN Customer id 2 Customer name Balu Customer address Chennai,TN
  • 6. Class Inheritance ● Inheritance From Base Class: ● class Parent def implicit() puts "Hello Parent" end ● end ● class Child < Parent ● end dad = Parent.new() son = Child.new() dad.implicit() son.implicit() ● Output: Hello Parent Hello Parent
  • 7. Inheritance Example ● class Parent def override() puts "Hi Parent" end ● end ● class Child < Parent def override() puts "Hi Child" end ● end dad = Parent.new() son = Child.new() dad.override() son.override() ● Output: Hi Parent Hi Child
  • 8. Ruby Variables ● Ruby Global Variables: Global variables begin with $. ● Example: $global_variable=100 ● Ruby Instance Variables: Instance variables begin with @. ● Example: @instance_variable=200 ● Ruby Class Variables: Class variables begin with @@ and must be initialized before they can be used in method definitions. ● Example: @@class_variable=300
  • 9. Ruby Arrays ● Creating an Array: a=[1,2,3,4,5] ( or) ● ary=Array.new ary[0]=1 ary[1]=2 ary[2]=3 ● arr = ['a', 'b', 'c', 'd', 'e', 'f']
  • 10. Accessing Array ● Accessing Element: arr = [1, 2, 3, 4, 5, 6] ● arr[2] # 3 ● arr[100] # nil ● arr[-3] # 4 ● arr[2, 3] #[3, 4, 5] ● arr[1..4] #[2, 3, 4, 5] ● arr.take(3) # [1, 2, 3] ● arr.drop(3) # [4, 5, 6] ● arr.at(0) # 1 ● arr.first # 1 ● arr.last # 6
  • 11. Adding Items to Arrays ● For adding can use either push or << ● arr = [1, 2, 3, 4] ● arr.push(5) #[1, 2, 3, 4, 5] ● Arr << 6 #[1, 2, 3, 4, 5, 6] ● Add a new item to the beginning of an array: ● arr.unshift(0) # [0, 1, 2, 3, 4, 5, 6] ● Add a new element to an array at any position: ● arr.insert(3, 'apple') #[0, 1, 2, 'apple', 3, 4, 5, 6] ● arr.insert(3, 'orange', 'pear', 'grapefruit') #[0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
  • 12. Removing Items from an Array ● arr = [1, 2, 3, 4, 5, 6] ● arr.pop # 6 ● arr # [1, 2, 3, 4, 5] ● arr.shift # 1 ● arr # [2, 3, 4, 5] ● To delete an element at a particular index: ● arr.delete_at(2) # 4 ● Arr # [2, 3, 5] ● To delete a particular element anywhere in an array: ● arr = [1, 2, 2, 3] ● arr.delete(2) # 2 ● arr # [1,3]
  • 13. Iteration in Array ● Ruby each: ● ary = [1,2,3,4,5] ary.each do |i| puts i end ● Ruby collect: ● a = [1,2,3,4,5] b = a.collect { |x| 10*x } puts b ● O/P: ● 1 2 3 4 5 ● O/P: ● 10 20 30 40 50
  • 14. Iteration in Array ● Ruby map: ● arr.map { |a| 2*a } # [2, 4, 6, 8, 10] ● arr # [1, 2, 3, 4, 5] ● arr.map! { |a| a**2 } # [1, 4, 9, 16, 25] ● arr # [1, 4, 9, 16, 25]
  • 15. .each with index in Array ● a=[1,2,3,4,5] a.each_with_index do |value, index| puts "#{index} index value is #{value}!" end ● Output: 0 index value is 1! 1 index value is 2! 2 index value is 3! 3 index value is 4! 4 index value is 5!
  • 16. Iteration in Array ● Selecting Element: ● arr = [1, 2, 3, 4, 5, 6] ● arr.select { |a| a > 3 } #[4, 5, 6] ● arr.reject { |a| a < 3 } #[3, 4, 5, 6] ● Delete Element: ● arr.delete_if { |a| a < 4 } # [4, 5, 6] ● Arr # [4, 5, 6]
  • 17. Operations in Array ● Remove Array: ● a = [ "a", "b", "c", "d", "e" ] a.clear # [ ] ● Count: ● ary = [1, 2, 4, 2] ary.count # 4 ● Delete: ● a = [ "a", "b", "b", "b", "c" ] a.delete("b") # "b" a # ["a", "c"] ● Delete_at: ● a = ["ant", "bat", "cat", "dog"] a.delete_at(2) # "cat" a #["ant", "bat", "dog"] ● Drop: ● a = [1, 2, 3, 4, 5, 0] a.drop(3) # [4, 5, 0] ● Join: ● [ "a", "b", "c" ].join # "abc" ● [ "a", "b", "c" ].join("-") # "a-b-c"
  • 18. Ruby Hashes ● Hashes are similar to arrays. Here we can create a values and keys. ● Creating Hash: ● grade = { "Alex" => 10, "Balu" => 6 } ● grade=Hash["a", 100, "b", 200] ● grade=Hash["a" => 100, "b" => 200] ● h = Hash.new() h["a"] = 100 h["b"] = 200 h #{"a"=>100, "b"=>200} ● Accessing Hash: ● h = { "a" => 100, "b" => 200 } h[“a”] # 100 h[“c”] # nil h[“b”] #200
  • 19. .each in Hash ● h = { "a" => 100, "b" => 200 } h.each { |key, value| puts "#{key} is #{value}" } ● Output: a is 100 b is 200 ● h = { "a" => 100, "b" => 200 } h.each_key {|key| puts key } ● Output: a b ● h = { "a" => 100, "b" => 200 } h.each_value {|value| puts value } ● Output: 100 200 ● h.has_key?("a") #true ● h.has_key?("z") #false ● h.has_value?(100) # true ● h.has_value?(999) # false
  • 20. Ruby if,Else if Stmt ● Ruby If: ● if var == 10 print “Variable is 10″ end ● Ruby Else If: ● x=5 if x > 2 puts "x is greater than 2" elsif x <= 2 puts "x is #{x}" else puts "I can't guess the number" end # x is greater than 2 ● Unless stmt: ● x=5 unless x>2 puts "x is less than 2" else puts "x is greater than 2" end ● #x is greater than 2
  • 21. Hash Example with argument ● def hash_arg(opt={}) alpha={ :a=>'Apple', :b=>'Banana', :c=>'Carrot', :d=>'Dog' }.merge(opt) puts "#{alpha[:a]} #{alpha[:b]} #{alpha[:c]} #{alpha[:d]}" puts opt puts alpha ● end hash_arg() hash_arg(:e => 'and') ● Output: ● Apple Banana Carrot Dog ● {} ● {:a=>"Apple", :b=>"Banana", :c=>"Carrot", :d=>"Dog"} ● Apple Banana Carrot Dog ● {:e=>"and"} ● {:a=>"Apple", :b=>"Banana", :c=>"Carrot", :d=>"Dog", :e=>"and"}
  • 22. Case Statement ● Case Stmt: age = 5 case age ● when 0..2 puts "baby" when 3..6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end ● Output: little child
  • 23. While and For loop ● While Loop: ● i = 0 while i < 5 do puts "Inside the loop i = #{i}" i +=1 end ● Output: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 ● For Loop: ● array=[0,1,2,3,4,5] ● for i in array puts "Value of i is #{i}" end ● Output: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
  • 24. Methods in Ruby ● Defining a Method with default argument: ● def test(a1="Ruby", a2="Java") puts "The programming language is #{a1}" puts "The programming language is #{a2}" ● end test "C", "C++" test ● Output: The programming language is C The programming language is C++ The programming language is Ruby The programming language is Java ● Defining a Method with Multiple argument: ● def some_method(a,b,*c,d) puts "A contain #{a}" puts "B contain #{b}" puts "c contain #{c}" puts "D contain #{d}" ● end some_method(5,4,2,1,6,7,8,9,3) ● Output A contain 5 B contain 4 c contain [2, 1, 6, 7, 8, 9] D contain 3
  • 25. Ruby Blocks ● Example: ● def test puts "You are in the method" yield puts "You are again back to the method" yield ● end test { puts "You are in the block" } ● Output: You are in the method You are in the block You are again back to the method You are in the block
  • 26. Ruby Blocks in Class Example: ● class Own_class < Array ● def double_each self.each do |element| yield(element*2) end ● end ● end d=Own_class.new([10, 20, 30, 40, 50]) d.double_each { |x| puts x } ● Output: 20 40 60 80 100

Hinweis der Redaktion

  1. * specify the variable length.