-
Notifications
You must be signed in to change notification settings - Fork 1
03 functions
Steve53 edited this page Sep 1, 2015
·
3 revisions
View the source code.
File
ruby functions.rb
Interpreter
$irb
irb(main):001:0> def greeting
irb(main):002:1> puts "Hello"
irb(main):003:1> end
=> nil
irb(main):004:0> greeting
Hello
=> nil
Demonstrates how to define functions and call them.
Some people say Ruby has no functions, only methods. Others use function to mean the kind of methods we define in this program.
def greeting
puts "Hello Steve"
end
We say these methods are defined at top-level. Methods defined at top-level become private instance methods of the Object class. Here, top-level is behaving like a class, not an instance of a class.
method(:greeting).owner #=> Object
Object.private_method_defined(:greeting) #=> true
For a discussion of how top-level sometimes behaves like an object and sometimes behaves like a class, see What is the Ruby Top-Level?.