SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
Basic Object 
Oriented Programming 
With Ruby!
Everything's An Object! 
"Hello, World!" # A String Object 
["one", "two"] # An Array Object 
# A Hash Object (with Symbol Object keys and String values!): 
{ 
username: "johndoe", 
password: "guessme" 
} 
1 # An Integer Object 
3.23421 # A Float Object
Objects Have State
Objects Have State 
State is basically data: the value or values that 
represent the aspects of the object. 
"Hello, World" 
# This object has only one piece of state, 
# a string of characters spelling "Hello World"
Objects Have State 
What is the state in a String object? 
# A String is an Array of characters 
"Hello".chars # => ['H', 'e', 'l', 'l', 'o']
Objects Have Methods
Objects Have Methods 
Methods operate on state: 
4 To change the state 
4 To return a changed copy of the state.
Objects Have Methods 
"Hello, World!".downcase # => "hello, world!" 
["one", "two"].reverse # => ["two", "one"] 
hash = { 
username: "johndoe", 
password: "guessme" 
} 
hash.delete(:username) # => "johndoe" 
hash # => {:password=>"guessme"} 
1.to_f # => 1.0 
3.23421.to_i # => 3
You Can Make Objects Too!
How To Write An Object 
4 "Class": another name for Object 
4 Objects are defined in files
How To Write An Object 
# File Name: better_string.rb 
class BetterString 
end 
Now we can make a BetterString: 
better_string = BetterString.new
How To Write An Object 
class BetterString 
def initialize(base) 
end 
end 
Now we can do: 
better_string = BetterString.new("A boring string") 
# Oh noes, our base string isn't saved! 
better_string.inspect # => "#<BetterString:0x007f8d7c1e6c78>"
How To Write An Object 
class BetterString 
def initialize(base) 
# This creates a LOCAL variable, only this method can see it 
base = base 
# This creates a INSTANCE variable (state) 
@base = base 
end 
end 
When you want to save state, use an instance variable.
How To Write An Object 
class BetterString 
def initialize(base) 
@base = base 
end 
end 
better_string = BetterString.new("A boring string") 
better_string.inspect 
# => "#<BetterString:0x007fa633091998 @base="A boring string">" 
better_string.base 
# ~> -:11:in `<main>': undefined method `base' for #<BetterString ...> (NoMethodError) 
# What gives?
Getters and Setters
Getters and Setters 
class BetterString 
def initialize(base) 
@base = base 
end 
# A getter for the @base variable 
def base 
@base 
end 
# A setter for the @base variable 
def base=(new_base) 
@base = new_base 
end 
end
Getters and Setters 
better_string = BetterString.new("A boring string") 
better_string.base # => "A boring string" 
better_string.base = "An awesome string" # => calls the base= setter 
better_string.base # => "An awesome string"
Shortcuts!
attr_reader, attr_writer 
class BetterString 
attr_reader :base # getter 
attr_writer :base # setter 
def initialize(base) 
@base = base 
end 
end
attr_accessor 
The shortcut to rule them all
attr_accessor 
class BetterString 
attr_accessor :base # both getter and setter! 
def initialize(base) 
@base = base 
end 
end
Review
Review 
4 Objects are a combination of state and methods 
4 You define classes in files 
4 Use @instance methods to save state 
4 Use attr_accessible, attr_writer, attr_reader to 
make getters and setters
So... 
Can we make BetterString 
DO SOMETHING?
Make Strings Awesome-er 
class BetterString 
# ... 
def improve 
@base.gsub("boring", "awesome") 
end 
end 
better_string = BetterString.new("A boring string") 
better_string.improve # => "A awesome string"
Class / Instance Methods
Class / Instance Methods 
Class: The Platonic definition of the object. 
Instance: A version of that object, assigned to a 
variable.
Class / Instance Methods 
BetterString # This is the class 
better_string = BetterString.new # This is an instance 
# Class methods can be called on the class 
BetterString.from_str("Some other string") 
# Instance methods can be called on instances 
better_string.improve
Class / Instance Methods 
class BetterString 
# This is a class method 
def self.from_str(other_string) 
BetterString.new(other_string) 
end 
# This is an instance method 
def improve 
# ... 
end 
end
Equality
Equality 
normal_string = "A boring string" 
better_string = BetterString.new("A boring string") 
normal_string == better_string # => false 
# Whaa??
Equality 
We can "overload" the == operator for BetterString. 
class BetterString 
# ... 
def ==(other_string) 
@base == other_string 
end 
end 
normal_string = "A boring string" 
better_string = BetterString.new("A boring string") 
normal_string == better_string # => true 
# Yay!
First Equality 
Then the World!
Operator Overloading 
We can override all kinds of operators for objects. 
4 Addition 
4 Subtraction 
4 Multiplication 
4 Division 
4 Equality
Review
Review 
4 Ruby is completely object-oriented 
4 Objects are a combination of state and methods 
4 Even operators are just methods!
A Note About Rails... 
Everything in Rails is a plain old Ruby Object. 
(PORO for short) 
Controllers, Models, Tests, they're all classes.
Go Forth and Conquer.

Mais conteúdo relacionado

Mais procurados

Generics. PECS
Generics. PECSGenerics. PECS
Generics. PECSUptech
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 TrainingChris Chubb
 
Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Augustin Bralley
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniquesDaniel Roseman
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Using and Abusing Magic methods in Python
Using and Abusing Magic methods in PythonUsing and Abusing Magic methods in Python
Using and Abusing Magic methods in PythonSlater Victoroff
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 

Mais procurados (20)

Generics. PECS
Generics. PECSGenerics. PECS
Generics. PECS
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
Array operators
Array operatorsArray operators
Array operators
 
ORM in Django
ORM in DjangoORM in Django
ORM in Django
 
Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
Values
ValuesValues
Values
 
Groovy
GroovyGroovy
Groovy
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Wp query
Wp queryWp query
Wp query
 
Advanced j query selectors
Advanced j query selectorsAdvanced j query selectors
Advanced j query selectors
 
Php variables
Php variablesPhp variables
Php variables
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Using and Abusing Magic methods in Python
Using and Abusing Magic methods in PythonUsing and Abusing Magic methods in Python
Using and Abusing Magic methods in Python
 
Advanced php
Advanced phpAdvanced php
Advanced php
 

Destaque

YWS open data presentation #WaterChallenge
YWS open data presentation #WaterChallengeYWS open data presentation #WaterChallenge
YWS open data presentation #WaterChallengeodileeds
 
Nitor Infotech - Big Data Services
Nitor Infotech - Big Data ServicesNitor Infotech - Big Data Services
Nitor Infotech - Big Data ServicesNitor Infotech
 
Halkla ilişkiler analiz
Halkla ilişkiler analizHalkla ilişkiler analiz
Halkla ilişkiler analizMelike Güneş
 
Drama in the making how to lay out working record
Drama in the making how to lay out working recordDrama in the making how to lay out working record
Drama in the making how to lay out working recordAarono1979
 
Betta Balustrades – Fulfilling all your fencing requirements in Australia
 Betta Balustrades – Fulfilling all your fencing requirements in Australia Betta Balustrades – Fulfilling all your fencing requirements in Australia
Betta Balustrades – Fulfilling all your fencing requirements in AustraliaBetta Balustrades
 
Tips for choosing balustrade for your home
Tips for choosing balustrade for your homeTips for choosing balustrade for your home
Tips for choosing balustrade for your homeBetta Balustrades
 
Evaluating questionnaires d2b1
Evaluating questionnaires d2b1Evaluating questionnaires d2b1
Evaluating questionnaires d2b1Aarono1979
 
Section c revision lesson
Section c revision lessonSection c revision lesson
Section c revision lessonAarono1979
 
Lookin headhunt gold rush 成長企業様向け資料
Lookin headhunt gold rush 成長企業様向け資料Lookin headhunt gold rush 成長企業様向け資料
Lookin headhunt gold rush 成長企業様向け資料Takahiro Nagafuchi
 
As media studies evaluation - for q1
As media studies evaluation - for q1As media studies evaluation - for q1
As media studies evaluation - for q1GeorgeTSulaiman
 
Armazenagem de mercadorias (1)
Armazenagem de mercadorias (1)Armazenagem de mercadorias (1)
Armazenagem de mercadorias (1)joaninha09
 
#Waterdata15
#Waterdata15#Waterdata15
#Waterdata15odileeds
 
E3c1 the job of a forensic psychologist
E3c1 the job of a forensic psychologistE3c1 the job of a forensic psychologist
E3c1 the job of a forensic psychologistAarono1979
 
Betta Balustrades Since - 1978
Betta Balustrades Since - 1978Betta Balustrades Since - 1978
Betta Balustrades Since - 1978Betta Balustrades
 

Destaque (16)

YWS open data presentation #WaterChallenge
YWS open data presentation #WaterChallengeYWS open data presentation #WaterChallenge
YWS open data presentation #WaterChallenge
 
Nitor Infotech - Big Data Services
Nitor Infotech - Big Data ServicesNitor Infotech - Big Data Services
Nitor Infotech - Big Data Services
 
Halkla ilişkiler analiz
Halkla ilişkiler analizHalkla ilişkiler analiz
Halkla ilişkiler analiz
 
Lookinheadhunt
LookinheadhuntLookinheadhunt
Lookinheadhunt
 
Drama in the making how to lay out working record
Drama in the making how to lay out working recordDrama in the making how to lay out working record
Drama in the making how to lay out working record
 
Sistem
SistemSistem
Sistem
 
Betta Balustrades – Fulfilling all your fencing requirements in Australia
 Betta Balustrades – Fulfilling all your fencing requirements in Australia Betta Balustrades – Fulfilling all your fencing requirements in Australia
Betta Balustrades – Fulfilling all your fencing requirements in Australia
 
Tips for choosing balustrade for your home
Tips for choosing balustrade for your homeTips for choosing balustrade for your home
Tips for choosing balustrade for your home
 
Evaluating questionnaires d2b1
Evaluating questionnaires d2b1Evaluating questionnaires d2b1
Evaluating questionnaires d2b1
 
Section c revision lesson
Section c revision lessonSection c revision lesson
Section c revision lesson
 
Lookin headhunt gold rush 成長企業様向け資料
Lookin headhunt gold rush 成長企業様向け資料Lookin headhunt gold rush 成長企業様向け資料
Lookin headhunt gold rush 成長企業様向け資料
 
As media studies evaluation - for q1
As media studies evaluation - for q1As media studies evaluation - for q1
As media studies evaluation - for q1
 
Armazenagem de mercadorias (1)
Armazenagem de mercadorias (1)Armazenagem de mercadorias (1)
Armazenagem de mercadorias (1)
 
#Waterdata15
#Waterdata15#Waterdata15
#Waterdata15
 
E3c1 the job of a forensic psychologist
E3c1 the job of a forensic psychologistE3c1 the job of a forensic psychologist
E3c1 the job of a forensic psychologist
 
Betta Balustrades Since - 1978
Betta Balustrades Since - 1978Betta Balustrades Since - 1978
Betta Balustrades Since - 1978
 

Semelhante a Ruby Classes

Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internalsWojciech Widenka
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesTchelinux
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testingVincent Pradeilles
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogrammingjoshbuddy
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 

Semelhante a Ruby Classes (20)

Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
1 the ruby way
1   the ruby way1   the ruby way
1 the ruby way
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 

Último

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Último (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Ruby Classes

  • 1. Basic Object Oriented Programming With Ruby!
  • 2. Everything's An Object! "Hello, World!" # A String Object ["one", "two"] # An Array Object # A Hash Object (with Symbol Object keys and String values!): { username: "johndoe", password: "guessme" } 1 # An Integer Object 3.23421 # A Float Object
  • 4. Objects Have State State is basically data: the value or values that represent the aspects of the object. "Hello, World" # This object has only one piece of state, # a string of characters spelling "Hello World"
  • 5. Objects Have State What is the state in a String object? # A String is an Array of characters "Hello".chars # => ['H', 'e', 'l', 'l', 'o']
  • 7. Objects Have Methods Methods operate on state: 4 To change the state 4 To return a changed copy of the state.
  • 8. Objects Have Methods "Hello, World!".downcase # => "hello, world!" ["one", "two"].reverse # => ["two", "one"] hash = { username: "johndoe", password: "guessme" } hash.delete(:username) # => "johndoe" hash # => {:password=>"guessme"} 1.to_f # => 1.0 3.23421.to_i # => 3
  • 9. You Can Make Objects Too!
  • 10. How To Write An Object 4 "Class": another name for Object 4 Objects are defined in files
  • 11. How To Write An Object # File Name: better_string.rb class BetterString end Now we can make a BetterString: better_string = BetterString.new
  • 12. How To Write An Object class BetterString def initialize(base) end end Now we can do: better_string = BetterString.new("A boring string") # Oh noes, our base string isn't saved! better_string.inspect # => "#<BetterString:0x007f8d7c1e6c78>"
  • 13. How To Write An Object class BetterString def initialize(base) # This creates a LOCAL variable, only this method can see it base = base # This creates a INSTANCE variable (state) @base = base end end When you want to save state, use an instance variable.
  • 14. How To Write An Object class BetterString def initialize(base) @base = base end end better_string = BetterString.new("A boring string") better_string.inspect # => "#<BetterString:0x007fa633091998 @base="A boring string">" better_string.base # ~> -:11:in `<main>': undefined method `base' for #<BetterString ...> (NoMethodError) # What gives?
  • 16. Getters and Setters class BetterString def initialize(base) @base = base end # A getter for the @base variable def base @base end # A setter for the @base variable def base=(new_base) @base = new_base end end
  • 17. Getters and Setters better_string = BetterString.new("A boring string") better_string.base # => "A boring string" better_string.base = "An awesome string" # => calls the base= setter better_string.base # => "An awesome string"
  • 19. attr_reader, attr_writer class BetterString attr_reader :base # getter attr_writer :base # setter def initialize(base) @base = base end end
  • 20. attr_accessor The shortcut to rule them all
  • 21. attr_accessor class BetterString attr_accessor :base # both getter and setter! def initialize(base) @base = base end end
  • 23. Review 4 Objects are a combination of state and methods 4 You define classes in files 4 Use @instance methods to save state 4 Use attr_accessible, attr_writer, attr_reader to make getters and setters
  • 24. So... Can we make BetterString DO SOMETHING?
  • 25. Make Strings Awesome-er class BetterString # ... def improve @base.gsub("boring", "awesome") end end better_string = BetterString.new("A boring string") better_string.improve # => "A awesome string"
  • 26. Class / Instance Methods
  • 27. Class / Instance Methods Class: The Platonic definition of the object. Instance: A version of that object, assigned to a variable.
  • 28. Class / Instance Methods BetterString # This is the class better_string = BetterString.new # This is an instance # Class methods can be called on the class BetterString.from_str("Some other string") # Instance methods can be called on instances better_string.improve
  • 29. Class / Instance Methods class BetterString # This is a class method def self.from_str(other_string) BetterString.new(other_string) end # This is an instance method def improve # ... end end
  • 31. Equality normal_string = "A boring string" better_string = BetterString.new("A boring string") normal_string == better_string # => false # Whaa??
  • 32. Equality We can "overload" the == operator for BetterString. class BetterString # ... def ==(other_string) @base == other_string end end normal_string = "A boring string" better_string = BetterString.new("A boring string") normal_string == better_string # => true # Yay!
  • 33. First Equality Then the World!
  • 34. Operator Overloading We can override all kinds of operators for objects. 4 Addition 4 Subtraction 4 Multiplication 4 Division 4 Equality
  • 36. Review 4 Ruby is completely object-oriented 4 Objects are a combination of state and methods 4 Even operators are just methods!
  • 37. A Note About Rails... Everything in Rails is a plain old Ruby Object. (PORO for short) Controllers, Models, Tests, they're all classes.
  • 38. Go Forth and Conquer.