1. Home
  2. Computing & Technology
  3. Perl

A short introduction to methods in Ruby - Beginning Ruby Tutorial
Ruby Methods

From About.com

A method in Ruby is an action taken on a specific object. You can also think of them as functions, but I find that thinking of them in the context of an action on an object helps keep the overall concepts of Ruby clear. A method is called using a . like so:
loaf_of_bread.slice
my_car.start
Here, the slice method is called on a loaf_of_bread, and the start method is run on my_car. Inside the object definitions for loaf_of_bread and my_car, there are method definitions (like functions, but related to a specific object) called slice and start.

Methods can be chained together simply by adding them to the call.

loaf_of_bread.slice.butter
my_car.start.drive
You can also pass arguments into a specific method.
my_car.start.drive('home')
Methods are typically defined in and for each individual object, but there is a special object called the Kernel in Ruby that all other objects inherit from. Kernel methods are accessed from anywhere in your Ruby scripts, and do not require the object name - if you've worked with even a small amount of Ruby, you've already seen several Kernel methods like print, chomp, and even your Ruby data types like Array and String.
  1. Everything in Ruby is an object, and methods are actions on those objects.
  2. Methods can be chained.
  3. Methods can be given arguments.
  4. A Kernel method is available anywhere in your script.
More Perl Quick Tips
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Similar Languages
  5. A short introduction to methods in Ruby, and how they are used

©2009 About.com, a part of The New York Times Company.

All rights reserved.