Skip to main content

Diigo Home

Ruby Programming/Ruby basics - Wikibooks, collection of open-content textbooks - The Diigo Meta page

en.wikibooks.org/...Ruby_basics - Cached - Annotated View

Benx Shen's personal annotations on this page

benxshen
Benxshen bookmarked on 2009-10-24
  • The function also returns a single value with the return keyword. Technically this isn't necessary -- the value of the last line executed in the function is used as the return value -- but more often than not using return explicitly makes things clearer.
  • Functions interact with blocks through the yield. Every time the function invokes yield control passes to the block. It only comes back to the function when the block finishes. Here's a simple example:


    # Script block2.rb

    def simpleFunction
    yield
    yield
    end

    simpleFunction { puts "Hello!" }

    $ block2.rb
    Hello!
    Hello!
  • The simpleFunction simply yields to the block twice -- so the block is run twice and we get two times the output. Here's an example where the function passes a parameter to the block:


    # Script block1.rb

    def animals
    yield "Tiger"
    yield "Giraffe"
    end

    animals { |x| puts "Hello, #{x}" }

    $ block1.rb
    Hello, Tiger
    Hello, Giraffe

This link has been bookmarked by 1 people . It was first bookmarked on 24 Oct 2009, by Benx Shen.

  • 24 Oct 09
    • The function also returns a single value with the return keyword. Technically this isn't necessary -- the value of the last line executed in the function is used as the return value -- but more often than not using return explicitly makes things clearer.
    • Functions interact with blocks through the yield. Every time the function invokes yield control passes to the block. It only comes back to the function when the block finishes. Here's a simple example:


      # Script block2.rb

      def simpleFunction
      yield
      yield
      end

      simpleFunction { puts "Hello!" }

      $ block2.rb
      Hello!
      Hello!
    • 1 more annotations...