Ruby Programming/Method Calling
super
[edit | edit source]The super keyword can be used to call a method of the same name in the superclass of the class making the call. Values passed to the super call are passed into the parent method.
Example:
class SomeClass def initialize(name) end end
class ChildClass < SomeClass def initialize(name, value) super(name) end end
A call to the initialize
function of the child class above will result in the execution of both its body and the body of the initialize
function in the parent class.
Note that if you invoke super without arguments, all arguments to executing method will be passed to the parent method as well - and if parent's signature does not match the number of arguments, an exception will be raised. So, if the child version of the method uses a different number of arguments than the version in superclass, you need to list arguments that you want to pass to the parent's version of the method.
Note also that you can use any method name, not just initialize (in this case).
iterators
[edit | edit source]Iterators provide a method for cycling through a set of values and performing an operation, usually specified by a code block, for each value. Iterator functionality is often provided through the mixin Enumeration
module.
The first iterator that Ruby programmers are likely to encounter is the each
iterator.
Example:
arr = [1,2,3] arr.each do |number| put number end
Outputs:
1 2 3
yield
[edit | edit source]yield
executes the entire code block passed to the method.
Example:
def do3times yield yield yield end do3times { puts "yielding..." }
Outputs:
yielding... yielding... yielding...
You can therefore make your own method looking like the built-in times
:
class Fixnum def times_plus1 i = 1 while i <= self + 1 i += 1 yield end end end
5.times_plus1 { puts "yielding..." }
Outputs:
yielding... yielding... yielding... yielding... yielding... yielding...