1 / 22

Learning Ruby

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

rachel
Download Presentation

Learning Ruby

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Methods Learning Ruby

  2. 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

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

  4. Random Numbers rand -> float greater than or equal to 0.0 and less than 1.0. rand(5) -> int in range 0..4 srand 1776 gives the random number generator a seed puts(Math::PI) #:: is scope resolution

  5. Defining own methods def sayMoonumberOfMoos puts 'mooooooo...'*numberOfMoos end # Note local variables def doubleThis num numTimes2 = num*2 puts num.to_s+' doubled is '+numTimes2.to_s end doubleThis 44 puts numTimes2.to_s # undefined variable

  6. Makes local copy def littlePestvar var = nil puts 'HAHA! I ruined your variable!' end var = 'You can\'t even touch my variable!‘ littlePestvar puts var

  7. Ruby Methods are Easy! 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 parameters tot=first rest.each{|val| tot +=val} tot  or return tot end paddThemAll( 1, 2, 3, 4, 5, 6, 7 )  28

  8. 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.

  9. Yield – calls provided block def yup yield yield yield end yup {puts "where is the beef?"} yield: calls the provided block where is the beef? where is the beef? where is the beef?

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

  11. Yield – reusing code (block can have parameters) def triple(max) yield 3*max end triple(8) { |x| print x, ", “} ->24

  12. Yield – reusing code what is output? def cubes(max) i=1 while i < max yield i**3 i += 1 end end cubes(8) { |x| print x, ", "} sum = 0 cubes(8) { |y| sum += y} print "\nsum=",sum product = 1 cubes(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.

  13. Yield – reusing code (output) def cubes(max) i=1 while i < max yield i**3 i += 1 end end cubes(8) { |x| print x, ", "} sum = 0 cubes(8) { |y| sum += y} print "\nsum=",sum product = 1 cubes(8) { |z| product *= z} print "\nproduct=",product 1, 8, 27, 64, 125, 216, 343, sum=784 product=128024064000 Scope of block passed is calling block not called block. sum is NOT known inside cubes but is known inside code block.

  14. Yield def compute( what ) if block_given? yield( what ) else what end # of if. end # of compute puts compute( 22 ) puts compute ( 11 ) { |num| num*num } puts compute (4 ) { |num| num+num } block_given? is built-in Return value is last thing executed 22 121 8

  15. 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 end end puts "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"]

  16. 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 end g = NumericSequences.new-> Creates instance of class g.fib(10) {|i,x| print "The #{i}thnumber: #{x}\n"}

  17. Using yield to print Fibonacci numbers 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 end g = NumericSequences.new g.fib(10) {|i,x| print "The #{i}th Fibonacci number: #{x}\n"} The 0th Fibonacci number: 0 The 1th Fibonacci number: 1 The 2th Fibonacci number: 1 The 3th Fibonacci number: 2 The 4th Fibonacci number: 3 The 5th Fibonacci number: 5 The 6th Fibonacci number: 8 The 7th Fibonacci number: 13 The 8th Fibonacci number: 21 The 9th Fibonacci number: 34 The 10th Fibonacci number: 55  allows two arguments to be used

  18. Return multiple values def give_back ( a, *b ) return a end # of give_back. pgive_back( 10 ) pgive_back( 10, 11 ) def give_back2 ( a, *b ) return a, b end first, rest = give_back2( 1, 2, 3, 4, 5 )

  19. 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)

  20. Classes • Array is a class • So is Hash

  21. Passing a class def create_from_factory(factory) factory.new end obj = create_from_factory(Array)

  22. 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 • def initialize(name, room) • @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

More Related