yields and blocks

In Ruby, methods may receive a code block in order to perform arbitrary segments of code.

When a method expects a block, it invokes it by calling the yield function.

This comes in hand when you want to iterate over a list or provide an own algorithm

example

class Person 
  def initialize( name ) 
     @name = name
end

  def do_with_name 
     yield( @name ) 
  end 
end

When you now invoke the Person class and pass a block

person = Person.new("johnlol")
person.do_with_name do |name|
   puts "Hey, his name is #{name}"
end

This would results obviously in

Hey, his name is johnlol

another example:

palin = %w(Lagerregal Rotor Otto Rentner)
person = Person.new(palin)
person.do_with_name do |name|
   puts name.reverse
end

Palindromlol..

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>