learning ruby

22
Learning Ruby Methods

Upload: rachel

Post on 23-Feb-2016

35 views

Category:

Documents


1 download

DESCRIPTION

Methods. Learning Ruby. Methods. We’ve seen several so far: puts, gets, chomp, to_s , and even +, -, * and / Usually use dot notation 5 + 5 is really just a shortcut way of writing 5.+  5 ‘pit ’ * 5 . String methods. lineWidth = 50 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Learning  Ruby

Learning Ruby

Methods

Page 2: Learning  Ruby

Methods

• We’ve seen several so far: puts, gets, chomp, to_s, and even +, -, * and /

• Usually use dot notation• 5 + 5 is really just a shortcut way of writing

5.+ 5• ‘pit ’ * 5

Page 3: Learning  Ruby

String methodslineWidth = 50puts( 'Old Mother Hubbard'.center(lineWidth))lineWidth = 40 str = '--> text <--' puts str.ljust lineWidth #parens are optional

Page 4: Learning  Ruby

Random Numbers

rand -> float greater than or equal to 0.0 and less than 1.0.

rand(5) -> int in range 0..4srand 1776 gives the random number generator

a seedputs(Math::PI) #:: is scope resolution

Page 5: Learning  Ruby

Defining own methodsdef sayMoo numberOfMoos puts 'mooooooo...'*numberOfMoos end # Note local variablesdef doubleThis num numTimes2 = num*2 puts num.to_s+' doubled is '+numTimes2.to_s end doubleThis 44puts numTimes2.to_s # undefined variable

Page 6: Learning  Ruby

Makes local copy

def littlePest var var = nil puts 'HAHA! I ruined your variable!' end var = 'You can\'t even touch my variable!‘littlePest var puts var

Page 7: Learning  Ruby

def addThem ( first, second )first + second The value of the last statement in the method is value returned, but you can also use “return”

end # of addThem.

puts addThem( 23, 6 ) 29

def addThemAll ( first, *rest ) variable number of parameterstot=firstrest.each{|val| tot +=val} tot or return totend

p addThemAll( 1, 2, 3, 4, 5, 6, 7 ) 28

Ruby Methods are Easy!

Page 8: Learning  Ruby

Scope• Local variables (begin with either an underscore or a lower

case letter) and are local to the code construct in which they are declared. For example, a local variable declared in a method or within a loop cannot be accessed outside of that loop or method.

• Global variables (begin with $) are accessible from anywhere in the Ruby program, regardless of where they are declared.

• A class variable (begins with @@) is shared amongst all instances of a class.

• Instance variables (begin with @) are similar to Class variables except that their values are local to specific instances of an object.

Page 9: Learning  Ruby

def yup yield yield yieldendyup {puts "where is the beef?"}

Yield – calls provided blockyield: calls theprovided block

where is the beef?where is the beef?where is the beef?

Page 10: Learning  Ruby

At Seats: what is output?

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"}

Page 11: Learning  Ruby

Yield – reusing code (block can have parameters)

def triple(max) yield 3*maxend

triple(8) { |x| print x, ", “} ->24

Page 12: Learning  Ruby

Yield – reusing code what is output?def cubes(max) i=1 while i < max yield i**3 i += 1 endend

cubes(8) { |x| print x, ", "}

sum = 0cubes(8) { |y| sum += y}print "\nsum=",sum

product = 1cubes(8) { |z| product *= z}print "\nproduct=",product

Scope of block passed is calling block not called block.

sum is NOT known inside cubes but is known inside code block.

Page 13: Learning  Ruby

Yield – reusing code (output)def cubes(max) i=1 while i < max yield i**3 i += 1 endend

cubes(8) { |x| print x, ", "}

sum = 0cubes(8) { |y| sum += y}print "\nsum=",sum

product = 1cubes(8) { |z| product *= z}print "\nproduct=",product

1, 8, 27, 64, 125, 216, 343, sum=784product=128024064000

Scope of block passed is calling block not called block.

sum is NOT known inside cubes but is known inside code block.

Page 14: Learning  Ruby

def compute( what )if block_given?

yield( what )else

whatend # of if.

end # of compute

puts compute( 22 )

puts compute ( 11 ) { |num| num*num }

puts compute (4 ) { |num| num+num }

Yield

block_given? is built-inReturn value is last thing executed

22

121

8

Page 15: Learning  Ruby

This is how each could be implemented via yieldself – current class “this”

class Array # Note how I can extend the functionality of built-in classes def my_each() 0.upto(length-1) do |i| yield self[i] call to provided code with my ith element end return self if want to use in assign statement or nest calls endendputs "Array\n"t = ["quit", "felt", "worry", "smith", "white", "abandon", "fish", "this", "oboe"]t.my_each{|i| print i, "\n" }p t.my_each{|i| print "The element is ", i, "\n" }.sort! -> prints elements then

["abandon", "felt", "fish", "oboe", "quit", "smith", "this", "white", "worry"]

Page 16: Learning  Ruby

What does this do?class NumericSequences def fib(limit) yield 0, 0 yield 1, 1 prev = 0 curr = 1 i=2 while (i <= limit) new = prev + curr yield i, new prev = curr curr = new i = i+1 end end endg = NumericSequences.new -> Creates instance of class g.fib(10) {|i,x| print "The #{i}th number: #{x}\n"}

Page 17: Learning  Ruby

Using yield to print Fibonacci numbersclass NumericSequences def fib(limit) yield 0, 0 yield 1, 1 prev = 0 curr = 1 i=2 while (i <= limit) new = prev + curr yield i, new prev = curr curr = new i = i+1 end end endg = NumericSequences.newg.fib(10) {|i,x| print "The #{i}th Fibonacci

number: #{x}\n"}

The 0th Fibonacci number: 0The 1th Fibonacci number: 1The 2th Fibonacci number: 1The 3th Fibonacci number: 2The 4th Fibonacci number: 3The 5th Fibonacci number: 5The 6th Fibonacci number: 8The 7th Fibonacci number: 13The 8th Fibonacci number: 21The 9th Fibonacci number: 34The 10th Fibonacci number: 55

allows two arguments to be used

Page 18: Learning  Ruby

def give_back ( a, *b )return a

end # of give_back.

p give_back( 10 )p give_back( 10, 11 )

def give_back2 ( a, *b )return a, b

endfirst, rest = give_back2( 1, 2, 3, 4, 5 )

Return multiple values

Page 19: Learning  Ruby

More ... Ruby So Far•Methods can take no arguments, a fixed number

of arguments, or a variable number of parameters as arguments•The value of the last statement executed is

returned by the method (unless an explicit return is used)

Page 20: Learning  Ruby

Classes

• Array is a class• So is Hash

Page 21: Learning  Ruby

Passing a class

def create_from_factory(factory) factory.new end

obj = create_from_factory(Array)

Page 22: Learning  Ruby

At seats – what does this do? Personalized chat room model

1. require "observer" 3. class Room 4. include Observable 6. def receive(message, sender) 7. changed 8. notify_observers(message, sender) 9. end 10. end

12. class Person 13. def initialize(name, room) 14. @name, @room = name, room 15. @transcript = "" 16. @room.add_observer(self) 17. end 19. attr_reader :transcript, :name 20. 21. def update(message, sender) 22. if sender == self 23. message = "Me: #{message}\n" 24. else 25. message = "#{sender.name}: #{message}\n" 26. end 27. 28. @transcript << message 29. end 30. 31. def says(message) 32. @room.receive(message, self) 33. end 34. end