Method Calls
super
Iterators
yield
Example:
Syntax:
Method calls invoke the method of the receiver (the value of the expression to the left of the dot). If no receiver is specified, calls the method of self.
Method names can be normal identifiers or identifiers followed by the character ? or !. Customarily, ? is used for predicates (methods returning true/false values), while ! is used for methods that are more destructive than their !-less counterparts (tr versus tr!).
If the last argument is preceded by *, the value of that expression is expanded to its arguments:
super
Example:
Syntax:
super calls the method that is being overridden by the current method. If the parentheses and arguments are omitted, the current method's arguments are passed to super as is. To call the overridden method without passing any arguments, indicate the parentheses as in super().
Iterators
Example:
Syntax:
Iterators are methods used for abstracting control structures (especially loops). If you call a method that is followed by a code segment enclosed by do ... end or by { ... } (called a block), the method can evaluate the block from within. Methods that call these kinds of blocks are called iterators. Block calls from iterators use yield. The value passed to yield is assigned to the variable between the two pipes ( | ).
{ ... } binds more strongly than a do ... end block.
Local variables that are first assigned (declared) in a block are only valid within that block.
Like most methods, an iterator's return value is nil if it is interrupted by break from within a block. When break has an argument, that value will become the iterator's return value.
yield
Example:
Syntax:
Passes the argument(s) as the block's argument(s) and evaluates the block. yield is used within MethodDefinition to define iterators.
Assignment of the block argument(s) is carried out according to the rules of multiple assignment. If no block is supplied to the method that executed yield (i.e., it is not an iterator), throws a LocalJumpError exception.
yield returns the result of the block's last evaluated expression. If block execution has been interrupted by next, returns nil. When next has an argument, that value will become yield's return value.
Last updated