Benx Shen's personal annotations on this page
-
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.
-
-
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...
-
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.