SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
Ruby 101
1
Thursday, April 18, 13
Topics
• Ruby Syntax
• Methods/Functions
• DataTypes
• Control Flow
• Exceptions
2
Thursday, April 18, 13
Ruby Syntax
3
Thursday, April 18, 13
Ruby Syntax
• indent 2 spaces, no tabs
• CamelCase for class names
• snake_case_for methods and variables
• filenames always snake case
user_setting.rb
class UserSetting
def update_from_params(params)
end
def save
end
end 4
Thursday, April 18, 13
Ruby Syntax
• comments start with #
• multi-line =begin =end
# one line comment
=begin
name = "Bob"
address = "123 street"
city = "Any Town"
=end
5
Thursday, April 18, 13
parentheses optional
(mostly!)
need them here
else will an OR here
Document.new "The Ruby Way", "Hal Fulton"
Document.new("The Ruby Way", "Hal Fulton")
event_date.to_s :short
event_date.to_s(:short)
if name.blank?
puts "Hi nobody"
end
if (name.blank? || (name == "bob"))
if name.blank? || (name == "bob")
if name.blank? || name == "bob"
6
Thursday, April 18, 13
one more thing about
parentheses
class User
def status
#blah blah
end
end
class User
def status()
#blah blah
end
end
always
never
7
Thursday, April 18, 13
Variables
8
$global_variable
@@class_variable
@instance_variable
CONSTANT
Thursday, April 18, 13
String Interpolation
vs String Concatenation
10.times { |n| puts "the number is #{n}" }
String Interpolation, plus reads better
10.times { |n| puts "the number is" + n }
String concatenation, slow-er!
plus calls to_s if not a string
9
Thursday, April 18, 13
• code style
• variable/class style
• comments
• role of parentheses
• variables
• string interpolation
10
Learned about Ruby Syntax
Thursday, April 18, 13
Methods
11
functions usually called methods
Thursday, April 18, 13
Method Return Values
12
def format_name(user)
return "#{user.first.capitalize} #{user.last.capitalize}"
end
def format_name(user)
"#{user.first.capitalize} #{user.last.capitalize}"
end
Last line of function is implicit return
Thursday, April 18, 13
methods with ? !
13
def validate_user?(user)
if user.first.present? && user.last.present?
true
else
false
end
end
def promote_user!(user, level)
user.access = level
user.save
end
Thursday, April 18, 13
methods with ?
14
> "classified ventures".include?("class")
=> true
> "classified ventures".include?("blah")
=> false
Use ? as part of the method name if it
returns a boolean
Thursday, April 18, 13
Using !
15
> company = "classified ventures"
=> "classified ventures"
> company.upcase
=> "CLASSIFIED VENTURES"
> company
=> "classified ventures"
> company.upcase!
=> "CLASSIFIED VENTURES"
> company
=> "CLASSIFIED VENTURES"
Thursday, April 18, 13
Learned about
• ! methods
• ? methods
• return value
16
Thursday, April 18, 13
Data Types
Everything is an object
no such idea as “primitives”
17
Thursday, April 18, 13
Strings
> company = "Classified Ventures"
=> "Classified Ventures"
> company.length
=> 19
> company.reverse
=> "serutneV deifissalC"
> company.upcase
=> "CLASSIFIED VENTURES"
> company.start_with?("Class")
=> true
> company.start_with?("Goo")
=> false
18
Thursday, April 18, 13
Symbols
> :first
=> :first
> :first.class
=> Symbol
Commonly used in Hashes
19
Thursday, April 18, 13
Whats the difference?
> "hello".object_id
=> 70312121540820
> "hello".object_id
=> 70312126306720
> :first.object_id
=> 32488
> :first.object_id
=> 32488
20
Thursday, April 18, 13
FixNum,
BigNum,Booleans
> 1.class
=> Fixnum
> 10000000000000000000000000.class
=> Bignum
> 3.14.class
=> Float
> true.class
=> TrueClass
> false.class
=> FalseClass
21
Thursday, April 18, 13
Arrays
fruits = ['apple', 'orange', 'pear']
fruits = %w(apple orange pear)
=> ['apple', 'orange', 'pear']
a = Array.new(5)
=> [nil, nil, nil, nil, nil]
a = Array.new(5, "--")
=> ["--", "--", "--", "--", "--"]
22
Thursday, April 18, 13
Hashes
default value if key is not found
fruits = {:apple => 5, :orange => 4, :pear => 1}
fruits = { apple: 5, orange: 4, pear: 1 }
fruits[:apple]
=> 5
z = {} #default is nil
a = Hash.new( "--" ) #default is “--”
z[:blah]
=> nil
a[:blah]
=> "--"
Ruby 1.9
23
Thursday, April 18, 13
Struct
24
Crumb = Struct.new(:name, :value)
=> Crumb
home = Crumb.new("Home", "/")
=> #<struct Crumb name="Home", value="/">
home
=> #<struct Crumb name="Home", value="/">
> home.name
=> "Home"
> home.value
=> "/"
Thursday, April 18, 13
Ranges
25
> 1..10
=> 1..10
> (1..10).class
=> Range
> (1..10).to_a (creates array)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> (1...10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
two dots includes end point
three dots does not include end point
Thursday, April 18, 13
Learned about Datatypes
• Strings
• Symbols
• FixNum, BigNum
• Booleans
• Array
• Hash
• Struct
• Ranges
26
Thursday, April 18, 13
Practice
• www.rubykoans.com
• http://www.zenspider.com/
Languages/Ruby/QuickRef.html
27
Thursday, April 18, 13
Classes
class Document
attr_accessor :title, :author, :content
def initialize(title, author, content)
@title = title
@author = author
@content = content
end
end
@var is an instance variable
access it as @var inside class
28
constructor
Thursday, April 18, 13
attr_accessor
makes getters and setters
class Document
# setter
def title=(title)
@title = title
end
# getter
def title
@title
end
class Document
attr_accessor :title
end
same result
also attr_reader and attr_writer
29
Thursday, April 18, 13
Example Class
class Document
attr_accessor :title, :author
def initialize(title, author)
@title = title
@author = author
end
def words
@content.split
end
def self.supported_file_types
%w(pdf jpg gif doc)
end
end
doc = Document.new("The Ruby Way", "Fulton")
doc.words
Document.supported_file_types
30
instance method
class method
Thursday, April 18, 13
Learned about
• class constructors
• getters/setters
• instance methods
• static methods
31
Thursday, April 18, 13
Control Flow
32
Thursday, April 18, 13
Code Blocks
10.times { |n| puts "the number is #{n}" }
10.times do |n|
puts "the number is #{n}"
better_for_longer_blocks(n)
end
33
item for each iteration is n
Thursday, April 18, 13
if / unless
if not @readonly
doc.write(text)
end
unless @readonly
doc.write(text)
end
unless @readonly
doc.write(text)
else
log.warn("attempt to write to readonly file")
end
doc.write(text) unless @readonly
bad
good
good
bad
34
Thursday, April 18, 13
for / each
fruits = ['apple', 'orange', 'pear']
for fruit in fruits
puts fruit
end
fruits.each do |fruit|
puts fruit
end
bad
good
35
Thursday, April 18, 13
while loops
36
i = 0
while i < 5
puts i
i += 1
end
i = 0
until i == 5
puts i
i += 1
end
puts i += 1 until i == 5
Thursday, April 18, 13
Exceptions
37
class Name
# Define default getter method, but not setter method.
attr_reader :first
# When someone tries to set a first name, enforce rules about it.
def first=(first)
if first.blank?
raise ArgumentError.new('Everyone must have a first name.')
end
@first = first.capitalize
end
end
def edit
name = Name.new
name.first = params[:name]
rescue ArgumentError => e
log.error("Validation Error #{e.message}")
end
Thursday, April 18, 13
Covered Control Flow
• if/unless
• for/each
• while loops
• exceptions
38
Thursday, April 18, 13

Weitere ähnliche Inhalte

Andere mochten auch

Introduccion al desarrollo de aplicaciones web con Ruby on Rails
Introduccion al desarrollo de aplicaciones web con Ruby on RailsIntroduccion al desarrollo de aplicaciones web con Ruby on Rails
Introduccion al desarrollo de aplicaciones web con Ruby on RailsAncorCruz
 
Ruby 101 && Coding Dojo
Ruby 101 && Coding DojoRuby 101 && Coding Dojo
Ruby 101 && Coding DojoGuilherme
 
Curso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasCurso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasAlberto Perdomo
 
Storage networking-technologies
Storage networking-technologiesStorage networking-technologies
Storage networking-technologiessagaroceanic11
 
Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reportssagaroceanic11
 

Andere mochten auch (9)

Introduccion al desarrollo de aplicaciones web con Ruby on Rails
Introduccion al desarrollo de aplicaciones web con Ruby on RailsIntroduccion al desarrollo de aplicaciones web con Ruby on Rails
Introduccion al desarrollo de aplicaciones web con Ruby on Rails
 
Ruby 101 && Coding Dojo
Ruby 101 && Coding DojoRuby 101 && Coding Dojo
Ruby 101 && Coding Dojo
 
Ruby 101
Ruby 101Ruby 101
Ruby 101
 
Ruby 101 session 3
Ruby 101 session 3Ruby 101 session 3
Ruby 101 session 3
 
Ruby 101 session 2
Ruby 101 session 2Ruby 101 session 2
Ruby 101 session 2
 
Curso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasCurso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticas
 
Storage networking-technologies
Storage networking-technologiesStorage networking-technologies
Storage networking-technologies
 
Ruby 101
Ruby 101Ruby 101
Ruby 101
 
Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reports
 

Ähnlich wie Ruby 101: Syntax, Methods, Data Types & Control Flow

Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.lrdesign
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object ClassPawanMM
 
Twig & D8 - DrupalCamp Baltics 2013 - Tallinn
Twig & D8 - DrupalCamp Baltics 2013 - TallinnTwig & D8 - DrupalCamp Baltics 2013 - Tallinn
Twig & D8 - DrupalCamp Baltics 2013 - TallinnSir-Arturio
 
Teach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry PiTeach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry PiJuan Gomez
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 

Ähnlich wie Ruby 101: Syntax, Methods, Data Types & Control Flow (11)

Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.
 
Scala 101-bcndevcon
Scala 101-bcndevconScala 101-bcndevcon
Scala 101-bcndevcon
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
Twig & D8 - DrupalCamp Baltics 2013 - Tallinn
Twig & D8 - DrupalCamp Baltics 2013 - TallinnTwig & D8 - DrupalCamp Baltics 2013 - Tallinn
Twig & D8 - DrupalCamp Baltics 2013 - Tallinn
 
Teach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry PiTeach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry Pi
 
Scala 101
Scala 101Scala 101
Scala 101
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 

Mehr von Nola Stowe

Austin Clojure: Clojure tools, Rebl readline
Austin Clojure: Clojure tools,  Rebl readlineAustin Clojure: Clojure tools,  Rebl readline
Austin Clojure: Clojure tools, Rebl readlineNola Stowe
 
Cool Things in Clojure 1.9
Cool Things in Clojure 1.9Cool Things in Clojure 1.9
Cool Things in Clojure 1.9Nola Stowe
 
Robot framework short talk
Robot framework short talkRobot framework short talk
Robot framework short talkNola Stowe
 
Women Who Code Functional Programming - 9/26/2016
Women Who Code   Functional Programming - 9/26/2016Women Who Code   Functional Programming - 9/26/2016
Women Who Code Functional Programming - 9/26/2016Nola Stowe
 
Beginning Clojure at AustinClojure Meetup
Beginning Clojure at AustinClojure MeetupBeginning Clojure at AustinClojure Meetup
Beginning Clojure at AustinClojure MeetupNola Stowe
 
Jekyll and MrBlog
Jekyll and MrBlogJekyll and MrBlog
Jekyll and MrBlogNola Stowe
 
Intro to Clojure 4 Developers
Intro to Clojure 4 DevelopersIntro to Clojure 4 Developers
Intro to Clojure 4 DevelopersNola Stowe
 
Intro to Clojure lightningtalk
Intro to Clojure lightningtalkIntro to Clojure lightningtalk
Intro to Clojure lightningtalkNola Stowe
 
Dart: Another Tool in the Toolbox
Dart: Another Tool in the ToolboxDart: Another Tool in the Toolbox
Dart: Another Tool in the ToolboxNola Stowe
 
Getting better through Katas
Getting better through KatasGetting better through Katas
Getting better through KatasNola Stowe
 
All girlhacknight intro to rails
All girlhacknight intro to railsAll girlhacknight intro to rails
All girlhacknight intro to railsNola Stowe
 

Mehr von Nola Stowe (12)

Austin Clojure: Clojure tools, Rebl readline
Austin Clojure: Clojure tools,  Rebl readlineAustin Clojure: Clojure tools,  Rebl readline
Austin Clojure: Clojure tools, Rebl readline
 
Cool Things in Clojure 1.9
Cool Things in Clojure 1.9Cool Things in Clojure 1.9
Cool Things in Clojure 1.9
 
Robot framework short talk
Robot framework short talkRobot framework short talk
Robot framework short talk
 
Women Who Code Functional Programming - 9/26/2016
Women Who Code   Functional Programming - 9/26/2016Women Who Code   Functional Programming - 9/26/2016
Women Who Code Functional Programming - 9/26/2016
 
Beginning Clojure at AustinClojure Meetup
Beginning Clojure at AustinClojure MeetupBeginning Clojure at AustinClojure Meetup
Beginning Clojure at AustinClojure Meetup
 
Jekyll and MrBlog
Jekyll and MrBlogJekyll and MrBlog
Jekyll and MrBlog
 
Intro to Clojure 4 Developers
Intro to Clojure 4 DevelopersIntro to Clojure 4 Developers
Intro to Clojure 4 Developers
 
Intro to Clojure lightningtalk
Intro to Clojure lightningtalkIntro to Clojure lightningtalk
Intro to Clojure lightningtalk
 
Dart: Another Tool in the Toolbox
Dart: Another Tool in the ToolboxDart: Another Tool in the Toolbox
Dart: Another Tool in the Toolbox
 
Getting better through Katas
Getting better through KatasGetting better through Katas
Getting better through Katas
 
Presenters
PresentersPresenters
Presenters
 
All girlhacknight intro to rails
All girlhacknight intro to railsAll girlhacknight intro to rails
All girlhacknight intro to rails
 

Kürzlich hochgeladen

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 

Kürzlich hochgeladen (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 

Ruby 101: Syntax, Methods, Data Types & Control Flow

  • 2. Topics • Ruby Syntax • Methods/Functions • DataTypes • Control Flow • Exceptions 2 Thursday, April 18, 13
  • 4. Ruby Syntax • indent 2 spaces, no tabs • CamelCase for class names • snake_case_for methods and variables • filenames always snake case user_setting.rb class UserSetting def update_from_params(params) end def save end end 4 Thursday, April 18, 13
  • 5. Ruby Syntax • comments start with # • multi-line =begin =end # one line comment =begin name = "Bob" address = "123 street" city = "Any Town" =end 5 Thursday, April 18, 13
  • 6. parentheses optional (mostly!) need them here else will an OR here Document.new "The Ruby Way", "Hal Fulton" Document.new("The Ruby Way", "Hal Fulton") event_date.to_s :short event_date.to_s(:short) if name.blank? puts "Hi nobody" end if (name.blank? || (name == "bob")) if name.blank? || (name == "bob") if name.blank? || name == "bob" 6 Thursday, April 18, 13
  • 7. one more thing about parentheses class User def status #blah blah end end class User def status() #blah blah end end always never 7 Thursday, April 18, 13
  • 9. String Interpolation vs String Concatenation 10.times { |n| puts "the number is #{n}" } String Interpolation, plus reads better 10.times { |n| puts "the number is" + n } String concatenation, slow-er! plus calls to_s if not a string 9 Thursday, April 18, 13
  • 10. • code style • variable/class style • comments • role of parentheses • variables • string interpolation 10 Learned about Ruby Syntax Thursday, April 18, 13
  • 11. Methods 11 functions usually called methods Thursday, April 18, 13
  • 12. Method Return Values 12 def format_name(user) return "#{user.first.capitalize} #{user.last.capitalize}" end def format_name(user) "#{user.first.capitalize} #{user.last.capitalize}" end Last line of function is implicit return Thursday, April 18, 13
  • 13. methods with ? ! 13 def validate_user?(user) if user.first.present? && user.last.present? true else false end end def promote_user!(user, level) user.access = level user.save end Thursday, April 18, 13
  • 14. methods with ? 14 > "classified ventures".include?("class") => true > "classified ventures".include?("blah") => false Use ? as part of the method name if it returns a boolean Thursday, April 18, 13
  • 15. Using ! 15 > company = "classified ventures" => "classified ventures" > company.upcase => "CLASSIFIED VENTURES" > company => "classified ventures" > company.upcase! => "CLASSIFIED VENTURES" > company => "CLASSIFIED VENTURES" Thursday, April 18, 13
  • 16. Learned about • ! methods • ? methods • return value 16 Thursday, April 18, 13
  • 17. Data Types Everything is an object no such idea as “primitives” 17 Thursday, April 18, 13
  • 18. Strings > company = "Classified Ventures" => "Classified Ventures" > company.length => 19 > company.reverse => "serutneV deifissalC" > company.upcase => "CLASSIFIED VENTURES" > company.start_with?("Class") => true > company.start_with?("Goo") => false 18 Thursday, April 18, 13
  • 19. Symbols > :first => :first > :first.class => Symbol Commonly used in Hashes 19 Thursday, April 18, 13
  • 20. Whats the difference? > "hello".object_id => 70312121540820 > "hello".object_id => 70312126306720 > :first.object_id => 32488 > :first.object_id => 32488 20 Thursday, April 18, 13
  • 21. FixNum, BigNum,Booleans > 1.class => Fixnum > 10000000000000000000000000.class => Bignum > 3.14.class => Float > true.class => TrueClass > false.class => FalseClass 21 Thursday, April 18, 13
  • 22. Arrays fruits = ['apple', 'orange', 'pear'] fruits = %w(apple orange pear) => ['apple', 'orange', 'pear'] a = Array.new(5) => [nil, nil, nil, nil, nil] a = Array.new(5, "--") => ["--", "--", "--", "--", "--"] 22 Thursday, April 18, 13
  • 23. Hashes default value if key is not found fruits = {:apple => 5, :orange => 4, :pear => 1} fruits = { apple: 5, orange: 4, pear: 1 } fruits[:apple] => 5 z = {} #default is nil a = Hash.new( "--" ) #default is “--” z[:blah] => nil a[:blah] => "--" Ruby 1.9 23 Thursday, April 18, 13
  • 24. Struct 24 Crumb = Struct.new(:name, :value) => Crumb home = Crumb.new("Home", "/") => #<struct Crumb name="Home", value="/"> home => #<struct Crumb name="Home", value="/"> > home.name => "Home" > home.value => "/" Thursday, April 18, 13
  • 25. Ranges 25 > 1..10 => 1..10 > (1..10).class => Range > (1..10).to_a (creates array) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > (1...10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9] two dots includes end point three dots does not include end point Thursday, April 18, 13
  • 26. Learned about Datatypes • Strings • Symbols • FixNum, BigNum • Booleans • Array • Hash • Struct • Ranges 26 Thursday, April 18, 13
  • 28. Classes class Document attr_accessor :title, :author, :content def initialize(title, author, content) @title = title @author = author @content = content end end @var is an instance variable access it as @var inside class 28 constructor Thursday, April 18, 13
  • 29. attr_accessor makes getters and setters class Document # setter def title=(title) @title = title end # getter def title @title end class Document attr_accessor :title end same result also attr_reader and attr_writer 29 Thursday, April 18, 13
  • 30. Example Class class Document attr_accessor :title, :author def initialize(title, author) @title = title @author = author end def words @content.split end def self.supported_file_types %w(pdf jpg gif doc) end end doc = Document.new("The Ruby Way", "Fulton") doc.words Document.supported_file_types 30 instance method class method Thursday, April 18, 13
  • 31. Learned about • class constructors • getters/setters • instance methods • static methods 31 Thursday, April 18, 13
  • 33. Code Blocks 10.times { |n| puts "the number is #{n}" } 10.times do |n| puts "the number is #{n}" better_for_longer_blocks(n) end 33 item for each iteration is n Thursday, April 18, 13
  • 34. if / unless if not @readonly doc.write(text) end unless @readonly doc.write(text) end unless @readonly doc.write(text) else log.warn("attempt to write to readonly file") end doc.write(text) unless @readonly bad good good bad 34 Thursday, April 18, 13
  • 35. for / each fruits = ['apple', 'orange', 'pear'] for fruit in fruits puts fruit end fruits.each do |fruit| puts fruit end bad good 35 Thursday, April 18, 13
  • 36. while loops 36 i = 0 while i < 5 puts i i += 1 end i = 0 until i == 5 puts i i += 1 end puts i += 1 until i == 5 Thursday, April 18, 13
  • 37. Exceptions 37 class Name # Define default getter method, but not setter method. attr_reader :first # When someone tries to set a first name, enforce rules about it. def first=(first) if first.blank? raise ArgumentError.new('Everyone must have a first name.') end @first = first.capitalize end end def edit name = Name.new name.first = params[:name] rescue ArgumentError => e log.error("Validation Error #{e.message}") end Thursday, April 18, 13
  • 38. Covered Control Flow • if/unless • for/each • while loops • exceptions 38 Thursday, April 18, 13