Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby Programming
Previous Page Home Next Page

Calling a Method

You call a method by specifying a receiver, the name of the method, and optionally some parameters and an associated block.

connection.downloadMP3("jitterbug") { |p| showProgress(p) }

In this example, the object connection is the receiver, downloadMP3 is the name of the method, "jitterbug" is the parameter, and the stuff between the braces is the associated block.

For class and module methods, the receiver will be the class or module name.

File.size("testfile")
Math.sin(Math::PI/4)

If you omit the receiver, it defaults to self, the current object.

self.id 537794160
id 537794160
self.type Object
type Object

This defaulting mechanism is how Ruby implements private methods. Private methods may not be called with a receiver, so they must be methods available in the current object.

The optional parameters follow the method name. If there is no ambiguity you can omit the parentheses around the argument list when calling a method.[Other Ruby documentation sometimes calls these method calls without parentheses ``commands.''] However, except in the simplest cases we don't recommend this---there are some subtle problems that can trip you up.[In particular, you must use parentheses on a method call that is itself a parameter to another method call (unless it is the last parameter).] Our rule is simple: if there's any doubt, use parentheses.

a = obj.hash    # Same as
a = obj.hash()  # this.

obj.someMethod "Arg1", arg2, arg3   # Same thing as obj.someMethod("Arg1", arg2, arg3)  # with parentheses.
Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire