Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby

How to create a function in Ruby

Hassaan Waqar

A function is a snippet of code that can be repeatedly used whenever it is called. We use functions to divide the functionality of a program into smaller parts that we can handle separately.

Basic syntax

Any generic function can be broken down into three parts:

Parts Description
Definition This is the first line that defines a function, gives it a name, and passes parameters (if available).
Body The code within the function.
Return statement This returns a calculated value or some solution.

Syntax

A function in Ruby is created as follows:

def myFunc(param)
 body
return <value>
end

The end keyword is used to mark the end of a function in Ruby.

Calling a function

A function is called using its name and passing in parameter values (if the function requires).

We can call the function myFunc, as follows:

value = myFunc(myParam)

The variable value will store the value returned by the myFunc function.

Example

The example here shows how we can create a function in Ruby:

The myFunc function takes in a number, prints it, and returns the number’s double.

# Creating a Function
def myFunc(num)
puts "The number is: ", num
return num * 2
end

# Calling the function
value = myFunc(4)
# Printing return value
puts "Returned valued is: ", value

RELATED TAGS

ruby

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring