Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 6 / 68

Writing a Method (Function)

In this lesson you will learn how to define a method in Ruby, and understand its implicit return value. This is for anyone searching for "Ruby method how to create" or "Ruby def".

def / end defines a method. The last expression evaluated automatically becomes the return value. Not having to state a return type is part of what lets you develop quickly, trying code as you go.

In the sample code the greet method evaluates the string "Welcome, #{name}!" last, so that string automatically becomes the return value without any return.

A common stumbling block for beginners is that until you are used to the implicit return, it is hard to see where the return value is decided. Keeping the rule "the last expression evaluated in the method is the return value" in mind makes the flow much easier to follow.

Giving a parameter a default value makes it easy to design flexible methods for the caller. In practice this kind of concise notation is part of what makes Ruby so productive.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)