Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

Method Parameters

You may have noticed that some methods (such as gets, reverse, to_s, and so on) can just be called on an object. However, other methods (such as +, -, puts…) take parameters to tell the object how to do the method. For example, you wouldn’t just say 5+, right? You’re telling 5 to add, but you aren’t telling it what to add.

To add a parameter to say_moo (let’s say, the number of moos), we would do the following:

def​ say_moo number_of_moos
puts ​'mooooooo...'​*number_of_moos
end
say_moo 3
puts ​'oink-oink'
# This last line should give an error
# because the parameter is missing...
say_moo
mooooooo...mooooooo...mooooooo...
oink-oink
example.rb:1:in `say_moo': wrong number of arguments (0 for 1) (ArgumentError)
from example.rb:10:in ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata