You can use the yield command to call a
Proc anywhere in the method and have computation afterwards.
In addition you can yield several times. I.e. you can call the given Proc with various arguments.
The
return command stops the method and returns a value.
To show you a case where using
returns is more bothersome than yielding values look at this excerpt from my
Linked_List class
#--------------------------------------------------------------------------
# * Name : Each
# Info : The each method required by the Enumerable module
# Author : Zeriab
# Call Info : Refer to the documentation on the Enumerable module
#--------------------------------------------------------------------------
def each
# Return if there are no elements in the list
return if self.head.nil?
# Yield the first value of the list (The head)
element = self.head
yield element.value
# Run through the list until the tail is fount or the next element of the
# list is nil
while element != self.tail && element.next_element != nil
# Retrieve and yield the next element in the list
element = element.next_element
yield element.value
end
end
This yields each value in the linked list. Basically the given piece of code is executed on each value in the list.
How would you do this with returns? How should you alter the code that calls the .each?
I hope this will help you understand more about yields and returns. I can go more in depth into how it works, but I won't do so if you are able to see where I am getting at with this.
In addition you can google
Visitor Design Pattern to help you understand how the principle behind the .each method and how passing blocks and yielding helps in this aspect.
*hugs*
- Zeriab