Hello Again Ruby - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

Hello Again Ruby

Description:

Whitespace is not significant (unlike Python) Statements separated by ... Reminder: Using ri and irb from the shell. irb, interactive Ruby interpreter ... – PowerPoint PPT presentation

Number of Views:80
Avg rating:3.0/5.0
Slides: 32
Provided by: radlabCs
Category:
Tags: again | hello | reminder | ruby

less

Transcript and Presenter's Notes

Title: Hello Again Ruby


1
Hello (Again) Ruby
2
Things to Review
  • Syntax conventions
  • Class methods/variables vs. Instance
    methods/variables
  • Mix-ins and Modules
  • Closures, Yield, and Blocks

3
CS61A Keywords of the Day
  • Symbol
  • Environment

4
Review Naming Conventions Syntax
  • ClassNames
  • class NewRubyProgrammer ... end
  • method_names and variable_names
  • def learn_conventions ... end
  • predicate_like_methods?
  • def is_faculty_member? ... end
  • dangerous_methods!
  • def brainwash_with_ruby! ... end
  • symbols
  • favorite_framework rails
  • Symbol or string? use to_sym and to_s to convert
    between.
  • SOME_CONSTANTS or OtherConstants
  • result in warning if reassigned after init

5
Review Syntax
  • Syntax features
  • Whitespace is not significant (unlike Python)
  • Statements separated by semicolons or newlines
  • Statement can span a newline
  • Parentheses can often be omitted
  • when unambiguous to parser use caution!!
  • raise "D'oh!" unless valid(arg)
  • raise "D'oh!" unless valid arg
  • raise "D'oh!" unless valid(arg)
  • Advice use a good text editor

6
Review Hashes
  • h "key" gt 1, value gt "foo"
  • h.has_key?("key") gt true
  • h"not a key" gt nil (not an error!)
  • h.delete(value) gt "key" gt 1
  • h.merge( key2 gt "3", "hi" gt blah )gt
    "key"gt 1, "key2" gt 3, hi gt blah
  • Ruby Rails idioms
  • omitting braces when a function takes a hash as
    its last argument
  • omitting parens around function arguments
  • link_to "Edit student", controllergt'students',
    actiongt'edit'
  • link_to("Edit student", controllergt'students',
    actiongt'edit')
  • Warning! if ambiguous parse...better safe than
    sorry!

7
Administrivia Break
  • 5um signup
  • Lab 0
  • Self-diagnostic quiz on web page
  • Books - see course homepage too
  • more or less required Agile Web Development with
    Rails, 2nd ed.
  • Programming Ruby (free, online at
    rubycentral.org/book)
  • or The Ruby Way by Fulton

8
Reminder Using ri and irb from the shell
  • irb, interactive Ruby interpreter
  • follow along with the examples!
  • ri (Ruby info) is like man
  • ri Comparable
  • ri gsub
  • ri Stringgsub
  • Note, need to be in a shell that has PATH and
    environment variables set correctly
  • See www.ruby-doc.org for more good documents

9
EVERYTHING IS AN OBJECT
10
Everything is an object (almost) everything is a
method call
  • Everything is an object
  • Even integers (try 57.methods)
  • Even nil (try nil.respond_to?(to_s))
  • (almost) every operator is really a method call
  • my_str.length gt my_str.send(length)
  • mymethod(foo) gt self.send(mymethod, foo)
  • 1 2 gt 1.send(, 2)
  • arr4 gt arr.send( , 4)
  • arr3 foo gt arr.send( , 3, foo)
  • if (x 3) gt if (x.send(, 3))

11
Nanoquiz
  • What happens?
  • x"foo"
  • puts 5x
  • puts "5"x

12
Classes Methods
  • Methods for MyBank.com
  • class Account
  • _at__at_bank_name "MyBank.com"
  • constructor is always called initialize
  • def initialize(starting_balance0)
  • _at_balance starting_balance
  • end
  • instance methods
  • def balance
  • _at_balance
  • end
  • def deposit(amount)
  • _at_balance amount
  • end
  • def withdraw(amount)
  • _at_balance - amount
  • end
  • A class method
  • def self.bank_name

13
Instance methods, not instance variables
  • Lets try a few...
  • my_account._at_balance
  • my_account.balance
  • my_account.balance 100
  • _at__at_bank_name
  • other_account Account.new(0)
  • other_account.bank_name
  • Account.bank_name
  • ...got it?

14
Instance variables shortcut
  • class Foo
  • def initialize(bar,baz)
  • _at_bar,_at_bazbar,baz
  • end
  • def bar _at_bar end
  • def baz _at_baz end
  • def bar(newbar) _at_barnewbar end
  • def baz(newbaz) _at_baznewbaz end
  • end

15
Instance variables shortcut
  • class Foo
  • def initialize(bar,baz)
  • _at_bar,_at_bazbar,baz
  • end
  • attr_accessor bar, baz
  • end

16
Pitfall
  • class Account
  • def empty_1
  • balance 0.0 warning!!
  • end
  • def empty_2
  • _at_balance 0.0 OK
  • end
  • def empty_3
  • self.balance 0.0 also ok, but different
  • end
  • end

17
REMEMBER!
  • a.b means call method b on object a
  • a is the receiver to which you send the method
    call, assuming a will respond to that method
  • does not mean b is an instance variable of a
  • does not mean a is some kind of structure of
    which b is a member
  • Understanding this distinction will save you from
    much grief and confusion

18
There are (almost) no Loops
  • Objects manage their own traversal
  • (1..10).each x ... gt range traversal
  • my_array.each elt ... gt array traversal
  • hsh.each_key key ... hsh.each_pair
    key,val .. gt hash traversal
  • 10.times ... gt iterator of arity zero
  • 10.times do ... end
  • ... is a synonym for do...end

19
Iterators
  • Consider a simple linear array...
  • you can enumerate its elements
  • you can perform operations on the collection
    (find, delete_if, sort elements, etc.)
  • Now consider a BinaryTree data structure
  • instance vars left child, right child
  • each child is either a BinaryTree or something
    elsea leaf node
  • in principle, should support many of same
    operations as array!

20
Ruby-think
  • How would you go about coding a library to
    support operations like find, delete_if, sort,
    etc.?
  • Hint 1 (bad) how does sort() library function
    work in ANSI C?
  • Hint 2 (good) what properties of an Array allow
    you to do these things?
  • its enumerable
  • its enumerability gives rise to all the other
    stuff
  • Can we do that in a generic way for a BinaryTree
    as well?

21
Ruby-think, cont.
  • The problem in thinking imperatively is that we
    dont know what we will want to do with the
    elements when we enumerate them.
  • An iterator separates the concept of enumerate
    the elements from the concept of doing
    something inside that loop.

22
How iterators solve this problem
23
Heres how to use it...
  • The iterator yields a value to the block
  • The block executes in the environment in which it
    was originally defined
  • The block is called a closure

24
How about sorting, find, ...?
  • Simple! just include the module Enumerable
  • Module methods get mixed in to BinaryTree class
  • Contract module expects BinaryTree objects to
    respond_to each, and it provides the other
    methods
  • If you want sorting, include Comparable and make
    sure the things to be compared respond_to ltgt

25
Mix-in example Comparable
  • Example Define ltgt method for your class
  • include Comparable
  • methods in Comparable get mixed in (added to) the
    target class that did the include
  • methods in Comparable assume that objects of
    target class respond to ltgt
  • doesnt actually matter what the class is!
  • Now, get lt lt gt gt between? for free
  • and, your class can now be sorted (by mixing in
    Enumerable...what do you suppose it assumes?)
  • Enumerable also provides all?, any?, collect,
    find, include?, inject, map, partition, ....

26
Duck Typing Makes it Possible
  • Ruby type set of values set of operations
  • A ruby module defines...
  • a collection of behaviors
  • that depend only on the presence of one or more
    specific existing behaviors
  • i.e. If it looks like a duck and walks like a
    duckgt it responds to the same methods as a
    duck.
  • Note, a module ? a class
  • but module methods can get mixed in to classes

27
Blocks
  • Iterators are just one use of closures
  • For other interesting ones, check out
  • open method of File class
  • form_tag helper method in Rails
  • Exercise implement times in a module
  • n3
  • n.times print "Ho" gt HoHoHo
  • How would you go about this?

28
Summary Rubys Distinguishing Features
  • Object-oriented with single inheritance
  • everything is an object
  • almost everything is a method call
  • Modules play a role similar to Javas interfaces
    and enable duck typing
  • Dynamically typed
  • Objects have types variables dont
  • very few operators in the language most are
    defined as instance methods on objects
  • Idiomatically, and () sometimes optional

29
Variables Methods
  • Variables have no type objects do
  • variables spring into existence on first
    assignment
  • nil,false are Boolean false everything else true
  • Everything is passed-by-reference
  • can use clone method to effect pass-by-value
  • except Fixnums...
  • Defining methods
  • def foo(x) x,x1 end
  • def foo(x)
  • x,x1
  • end
  • def foo(x)
  • return x,x1
  • end

30
Arrays
  • x 3, 'a', "third", blah, last
  • x0 gt 3
  • x-1 gt last
  • x-2 gt blah
  • x-3..-1 gt "third", blah, last
  • y 1,2
  • y 3,4 gt 1,2,3,4
  • y ltlt 5 gt 1,2,3,4,5
  • y ltlt 6,7 gt 1,2,3,4,5,6,7
  • Note! These are nearly all instance methods of
    Arraynot language operators!

31
Hashes and function calls
  • Immediate hash (any object can be a key, any
    object can be an attribute)
  • my_hsh foo gt 1, "x" gt nil, 3 gt 'a',4
  • my_hshnonexistent_key returns nil
  • Parens can be omitted from function calls if
    parsing is unambiguous
  • x foo(3, "no") ? x foo 3, "no"
  • Braces can be omitted from hash if parsing is
    unambiguous
  • x foo( agt1,bgt2) ? x foo(agt1,bgt2)
  • easy way to do keyword arguments
  • Caveat passing immediates to a function that
    accepts multiple hashes as its arguments
Write a Comment
User Comments (0)
About PowerShow.com