Methods

Contents
Define and call
Arguments
Defaults and kwargs
Implicit return

Define and call

The keyword def opens a method and end closes it. Method names use snake case, with words joined by underscores. Call the method by writing its name, with or without parentheses.

def greet puts "hello" end greet

hello

Arguments

Names listed in parentheses become required arguments, and the call must supply the same count. Inside the body, each argument behaves like an ordinary local variable.

def add(a, b) puts a + b end add(2, 3)

5

Defaults and kwargs

A default after the equals sign applies when the caller skips that argument. Keyword arguments carry names at the call site, so their order no longer matters. Use defaults for simple options and keywords when a method takes several settings.

def greet(name = "guest") puts "hello #{name}" end greet greet("Ada") def move(x:, y:) puts "#{x}, #{y}" end move(x: 1, y: 2)

hello guest
hello Ada
1, 2

Implicit return

Ruby returns the last evaluated expression, so most methods need no explicit return. The keyword return exits early with a value, which suits guard clauses. A method with nothing useful to give back returns nil.

def double(n) n * 2 end puts double(4) def sign(n) return "zero" if n == 0 "other" end puts sign(0)

8
zero

Next: Blocks, procs, lambdas

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: