Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Ruby Programming/Method Calling

From Wikibooks, open books for an open world
<Ruby Programming
This page may need to bereviewed for quality.

super

[edit |edit source]

Thesuper 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 theinitialize function of the child class above will result in the execution of both its body and the body of theinitialize function in the parent class.

Note that if you invokesuper 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 themixinEnumeration module.

The first iterator that Ruby programmers are likely to encounter is theeach 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-intimes:

 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...
Previous: Control StructuresIndexNext: Classes
Retrieved from "https://en.wikibooks.org/w/index.php?title=Ruby_Programming/Method_Calling&oldid=3353954"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp