SlideShare a Scribd company logo
Outline
•Three pillars of Ruby (§3.1)
•Everything is an object, and every operation
is a method call (§3.2–3.3)
•OOP in Ruby (§3.4)
•Reflection and metaprogramming (§3.5)
•Functional idioms and iterators (§3.6)
•Duck typing and mix-ins (§3.7)
•Blocks and Yield (§3.8)
Ruby 101(ELLS §3.1)
Armando Fox
© 2012 Armando Fox & David Patterson
Licensed under Creative Commons Attribution-
NonCommercial-ShareAlike 3.0 Unported
License
Ruby is...
•Interpreted
•Object-oriented
•Everything is an object
•Every operation is a method call on some object
•Dynamically typed: objects have types, but
variables  don’t
•Dynamic
•add, modify code at runtime (metaprogramming)
•ask objects about themselves (reflection)
•in a sense all programming is metaprogramming
Naming conventions
•ClassNames use UpperCamelCase
class FriendFinder ... end
•methods & variables use snake_case
def learn_conventions ... end
def faculty_member? ... end
def charge_credit_card! ... end
•CONSTANTS (scoped) & $GLOBALS (not scoped)
TEST_MODE = true $TEST_MODE = true
•symbols: immutable string whose value is itself
favorite_framework = :rails
:rails.to_s == "rails"
"rails".to_sym == :rails
:rails == "rails" # => false
Variables, Arrays, Hashes
•There are no declarations!
•local variables must be assigned before use
•instance & class variables ==nil until assigned
•OK: x = 3; x = 'foo'
•Wrong: Integer x=3
•Array: x = [1,'two',:three]
x[1] == 'two' ; x.length==3
•Hash: w = {'a'=>1, :b=>[2, 3]}
w[:b][0] == 2
w.keys == ['a', :b]
Methods
•Everything (except fixnums) is pass-by-reference
def foo(x,y)
return [x,y+1]
end
def foo(x,y=0) # y is optional, 0 if omitted
[x,y+1] # last exp returned as result
end
def foo(x,y=0) ; [x,y+1] ; end
•Call with: a,b = foo(x,y)or a,b = foo(x) when optional arg used
Basic Constructs
•Statements end with ';' or newline, but can
span line if parsing is unambiguous
✔raise("Boom!") unless ✖ raise("Boom!") (ship_stable)
unless (ship_stable)
•Basic Comparisons & Booleans: == != < > =~
!~ true false nil
• The usual control flow constructs
•
Strings & Regular Expressions(try rubular.com
for your regex needs!)
"string", %Q{string}, 'string', %q{string}
a=41 ; "The answer is #{a+1}"
•match a string against a regexp:
"fox@berkeley.EDU" =~ /(.*)@(.*).edu$/i
/(.*)@(.*).edu$/i =~ "fox@berkeley.EDU"
•If no match, value is false
•If match, value is non-false, and $1...$n capture
parenthesized groups ($1 == 'fox', $2 == 'berkeley')
/(.*)$/i or %r{(.*)$}i
or Regexp.new('(.*)$', Regexp::IGNORECASE)
•A real example... http://pastebin.com/hXk3JG8m
rx[:fox][1] =~ "ARMANDO"
rx['fox'][1] =~ "ARMANDO"
"armando" =~ rx['fox', 1]
"armando" =~ rx{:fox}
☐
☐
☐
☐
*
rx = {:fox=>/^arm/,
'fox'=>[%r{AN(DO)$}, /an(do)/i]}
Which expression will evaluate to non-nil?

More Related Content

PDF
Slides chapter3part1 ruby-forjavaprogrammers
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
PPTX
Ruby basics
PDF
Ruby 2: some new things
PDF
Ruby basics
PPT
Javascript
PDF
Functional programming in ruby
PPTX
Front end fundamentals session 1: javascript core
Slides chapter3part1 ruby-forjavaprogrammers
Code for Startup MVP (Ruby on Rails) Session 2
Ruby basics
Ruby 2: some new things
Ruby basics
Javascript
Functional programming in ruby
Front end fundamentals session 1: javascript core

Similar to CS169 UC Berkeley Armando Fox Ruby basics (20)

PPTX
Week 6 java script loops
PDF
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
PPT
Groovy unleashed
PPT
Intermediate JavaScript
PPT
Getting started in Python presentation by Laban K
PDF
Ruby — An introduction
PDF
Introduction to Python for Plone developers
PPT
Rubyforjavaprogrammers 1210167973516759-9
PPT
Rubyforjavaprogrammers 1210167973516759-9
PPTX
Introduction To PHP000000000000000000000000000000.pptx
PPT
Class 2 - Introduction to PHP
PPSX
Java Tutorial
PDF
Active Support Core Extensions (1)
PDF
Tutorial matlab
PDF
Tutorialmatlab kurniawan.s
PDF
Ruby_Basic
PDF
Matlab lec1
KEY
Learn Ruby 2011 - Session 3
PDF
Python Functions (PyAtl Beginners Night)
PDF
Introductionto fp with groovy
Week 6 java script loops
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
Groovy unleashed
Intermediate JavaScript
Getting started in Python presentation by Laban K
Ruby — An introduction
Introduction to Python for Plone developers
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
Introduction To PHP000000000000000000000000000000.pptx
Class 2 - Introduction to PHP
Java Tutorial
Active Support Core Extensions (1)
Tutorial matlab
Tutorialmatlab kurniawan.s
Ruby_Basic
Matlab lec1
Learn Ruby 2011 - Session 3
Python Functions (PyAtl Beginners Night)
Introductionto fp with groovy
Ad

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Cloud computing and distributed systems.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Approach and Philosophy of On baking technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation theory and applications.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Spectroscopy.pptx food analysis technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Network Security Unit 5.pdf for BCA BBA.
Cloud computing and distributed systems.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation_ Review paper, used for researhc scholars
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Machine learning based COVID-19 study performance prediction
Digital-Transformation-Roadmap-for-Companies.pptx
Unlocking AI with Model Context Protocol (MCP)
Diabetes mellitus diagnosis method based random forest with bat algorithm
Dropbox Q2 2025 Financial Results & Investor Presentation
MYSQL Presentation for SQL database connectivity
Approach and Philosophy of On baking technology
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation theory and applications.pdf
Big Data Technologies - Introduction.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectroscopy.pptx food analysis technology
Ad

CS169 UC Berkeley Armando Fox Ruby basics

  • 1. Outline •Three pillars of Ruby (§3.1) •Everything is an object, and every operation is a method call (§3.2–3.3) •OOP in Ruby (§3.4) •Reflection and metaprogramming (§3.5) •Functional idioms and iterators (§3.6) •Duck typing and mix-ins (§3.7) •Blocks and Yield (§3.8) Ruby 101(ELLS §3.1) Armando Fox © 2012 Armando Fox & David Patterson Licensed under Creative Commons Attribution- NonCommercial-ShareAlike 3.0 Unported License Ruby is... •Interpreted •Object-oriented •Everything is an object •Every operation is a method call on some object •Dynamically typed: objects have types, but variables  don’t •Dynamic •add, modify code at runtime (metaprogramming) •ask objects about themselves (reflection) •in a sense all programming is metaprogramming Naming conventions •ClassNames use UpperCamelCase class FriendFinder ... end •methods & variables use snake_case def learn_conventions ... end def faculty_member? ... end def charge_credit_card! ... end •CONSTANTS (scoped) & $GLOBALS (not scoped) TEST_MODE = true $TEST_MODE = true •symbols: immutable string whose value is itself favorite_framework = :rails :rails.to_s == "rails" "rails".to_sym == :rails :rails == "rails" # => false Variables, Arrays, Hashes •There are no declarations! •local variables must be assigned before use •instance & class variables ==nil until assigned •OK: x = 3; x = 'foo' •Wrong: Integer x=3 •Array: x = [1,'two',:three] x[1] == 'two' ; x.length==3 •Hash: w = {'a'=>1, :b=>[2, 3]} w[:b][0] == 2 w.keys == ['a', :b] Methods •Everything (except fixnums) is pass-by-reference def foo(x,y) return [x,y+1] end def foo(x,y=0) # y is optional, 0 if omitted [x,y+1] # last exp returned as result end def foo(x,y=0) ; [x,y+1] ; end •Call with: a,b = foo(x,y)or a,b = foo(x) when optional arg used Basic Constructs •Statements end with ';' or newline, but can span line if parsing is unambiguous ✔raise("Boom!") unless ✖ raise("Boom!") (ship_stable) unless (ship_stable) •Basic Comparisons & Booleans: == != < > =~ !~ true false nil • The usual control flow constructs • Strings & Regular Expressions(try rubular.com for your regex needs!) "string", %Q{string}, 'string', %q{string} a=41 ; "The answer is #{a+1}" •match a string against a regexp: "fox@berkeley.EDU" =~ /(.*)@(.*).edu$/i /(.*)@(.*).edu$/i =~ "fox@berkeley.EDU" •If no match, value is false •If match, value is non-false, and $1...$n capture parenthesized groups ($1 == 'fox', $2 == 'berkeley') /(.*)$/i or %r{(.*)$}i or Regexp.new('(.*)$', Regexp::IGNORECASE) •A real example... http://pastebin.com/hXk3JG8m rx[:fox][1] =~ "ARMANDO" rx['fox'][1] =~ "ARMANDO" "armando" =~ rx['fox', 1] "armando" =~ rx{:fox} ☐ ☐ ☐ ☐ * rx = {:fox=>/^arm/, 'fox'=>[%r{AN(DO)$}, /an(do)/i]} Which expression will evaluate to non-nil?