Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Methods in Ruby
3.
Method Arguments in Ruby
4.
Methods vs. Functions
5.
Arguments vs. Parameters
6.
Methods Without Arguments
6.1.
Code
7.
Output
8.
Positional Arguments
9.
Syntax
10.
Required Positional Arguments
10.1.
Code
10.2.
Output
11.
Optional Positional Arguments
11.1.
Code
11.2.
Output
12.
Variable Arguments
12.1.
Code
13.
Output
14.
Frequently Asked Questions
14.1.
What are the arguments in Ruby?
14.2.
How are arguments passed in Ruby?
14.3.
What is &block in Ruby?
14.4.
What's the difference between a parameter and an argument, Ruby?
14.5.
Do arguments in Ruby get passed by reference or by value?
15.
Conclusion
Last Updated: Mar 27, 2024
Medium

Method Arguments in Ruby

Author Apoorv
0 upvote

Introduction 

Ruby is an object-oriented programming language that is general-purpose, dynamic, and reflective. Except for blocks, which have replacements in the form of procs and lambda, everything in Ruby is an object. The goal of Ruby's development was to create a user interface between human programmers and the computational machinery that underpins them.

Ruby's syntax is similar to many other programming languages, including C and Java, making learning easy for Java and C programmers. It runs on various operating systems, including Windows, Mac OS X, and Linux.

Let's talk about Method Arguments in Ruby and how to do it in Ruby. So before going deeper into the topic, let's first understand the method in any programming language.

Methods in Ruby

Ruby methods are very similar to functions in any other programming language. A method is a group of statements that carry out a particular task and provide the outcome. Methods enable the user to reuse the code without typing it again, saving time. 

One or more repeated statements can be combined using Ruby methods. Lowercase letters should be used to start method names. Ruby may interpret a method name that starts with an uppercase letter as a constant and may erroneously parse the call if this happens. Now we are clear with how simple functions work in ruby, so we can move to method arguments in ruby.

Method Arguments in Ruby

Everything we need to do in Ruby is accomplished by calling methods on objects because it is an object-oriented language where everything is an object (even methods are objects of the class Method!). As a result of their widespread use, procedures also need to be highly flexible.

Simple method declarations follow the method name with a comma-separated list of argument names (in optional parentheses). But Ruby's method parameters are considerably more than that.

Ruby offers a variety of ways for us to give arguments for our methods, so we'll break this topic up into several parts to keep it manageable. The options will be divided into many categories, and everything will then be broken down with some examples and/or use cases.

Methods vs. Functions

Both methods and functions have the same role: easily encapsulate a piece of code. They are occasionally used interchangeably. However, there is a conceptual difference:

  • Functions should not rely on or change the status of external variables or inputs; they should only return results depending on the input.
  • A method can be called without any arguments since it always runs in the context of an object, but we can still access and change its state at any time.

In Ruby, because everything is an object, we can never have genuine functions, but if we want something comparable, we can create methods that won't use or affect the object's state.

Arguments vs. Parameters

The concepts of arguments and parameters are also important distinctions. The variables that will hold the values we use when calling a method are known as its parameters, and they are included in the specification of a method. When we call a method, arguments are the real values we provide. See this example here:

# Method Arguments in ruby
 def dummy_method(para)
  # para is a parameter when defining the method
end

dummy_method("CodingNinja")
# "CodingNinjas" is the argument we use when calling the method
You can also try this code with Online Ruby Compiler
Run Code


Most of the time, I'll use the word "arguments" for simplicity since a method defines the parameters and accepts arguments.

 

Know more Difference between argument and parameter in detail here.

Methods Without Arguments

The def keyword is used to define methods. After this, the method name and an optional list of parameter names are placed in parenthesis. The parameter list is followed by the Ruby code that makes up the method body, and the end keyword indicates the method's conclusion. The values of these named parameters originate from the arguments of a method invocation, and parameter names can be utilized as variables within the method body.

Code

# Ruby program to demonstrate the defining
# and calling of method in ruby
# Method Arguments in ruby
 
# Here Function name is defined with def keyword
def ninja
 
# This function will print this statement
puts "Welcome to Coding Ninjas Studio portal"
 
 
# keyword to end the method
end
 
# calling of the method
ninja
You can also try this code with Online Ruby Compiler
Run Code


In this code, we have defined our function without parameters, and this function will print the statement inside it.

Output

Welcome to Coding Ninjas Studio portal
You can also try this code with Online Ruby Compiler
Run Code

Positional Arguments

Arguments that must be presented in the right order or position are known as positional arguments. The first positional argument must always be listed when calling a function. It is necessary to specify the second positional argument second, the third positional argument third, etc.

Positional arguments can be 0 or more, and they can be both mandatory and optional.

Syntax

def my_method_name [( [argument [= default]]...[, * argument [, &expr ]])]
expr..
end
You can also try this code with Online Ruby Compiler
Run Code

Required Positional Arguments

Although it is not necessary to provide these positional arguments when defining the method, they must be provided when the method is called (you can have no arguments, only optional, etc.). You must offer a defence for each position if the technique specifies the necessary parameters. Lets' understand this with an example:

Code

# Method Arguments in ruby 
def positional_argument(arg1)
  puts "arg1 is: #{arg1.inspect}"
end

positional_argument("Coding Ninjas Studio")
You can also try this code with Online Ruby Compiler
Run Code


In this code, I pass one parameter and then call the function to print that parameter. Here we can also pass the multiple parameters in the function.

Output

arg1 is: “Coding Ninjas Studio”
You can also try this code with Online Ruby Compiler
Run Code

Optional Positional Arguments

Sometimes we want to let the user give additional input without making them feel obligated to. To do that, we can use optional arguments, each of which has a default value defined in the event the user doesn't provide one. This is very helpful when we want to give our method some default behavior while yet giving the user the ability to change it. We wouldn't have this flexibility if we simply hardcoded the default value inside the method. Let's understand this with the help of an example:

Code

# Method Arguments in ruby
def positional_argument(arg1 = 'default value')
  puts "argument 1 is: #{arg1.inspect}"
end

# => arg1 is: "Coding Ninjas Studio"
positional_argument("Coding Ninjas Studio")

# => arg1 is: default value
positional_argument
You can also try this code with Online Ruby Compiler
Run Code


In this piece of code, we have passed one parameter if the function has no parameters while the time of calling of function, in that case, it will print the default value.

Output

argument 1 is: “Coding Ninjas Studio”
argument 1 is: “default value”
You can also try this code with Online Ruby Compiler
Run Code

Variable Arguments

Sometimes we wish to create methods that can take any number of parameters. There is no default value for the optional positional arguments of this type. They can only be accessed via a unique array of arguments and only exist if they are assigned. When specifying the argument, we use the splat operator (*). Let's see this with the help of an example:

Code

# Method Arguments in ruby
def variable_argument(*args) # we use this special syntax with the * (splat operator) at the beginning of the paremeter
  puts "args is: #{args.inspect}"
end

# => args is: [1] ,list has one item
variable_argument(1)

# => args is: [1, 2] ,list has two items
variable_argument(1,2)

# => args is: [1, 2,3] ,list has three items
variable_argument(1,2,3)
You can also try this code with Online Ruby Compiler
Run Code


In this piece of code, as we can see here, we are passing multiple parameters and that variable length, and the function also accepts the same.

Check out this article - Balanced Parentheses

Output

args is: [1]
args is: [1, 2]
args is: [1, 2, 3]
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

What are the arguments in Ruby?

When you call a method in Ruby, every argument is necessary. A method that accepts a parameter cannot be called without an argument. Additionally, if more than one argument is passed when calling a method that only accepts one parameter, an error will be raised.

How are arguments passed in Ruby?

In a ruby programming language, the arguments are passed inside a method and by reference.

What is &block in Ruby?

Ruby code can be sent into a method using the &block, which is evaluated within the method's scope. According to the code in your example, a named partial cart will be displayed in a div.

What's the difference between a parameter and an argument, Ruby?

The variable in the function definition listed between parentheses is referred to as a parameter. When a function is called, a value is supplied as an argument.

Do arguments in Ruby get passed by reference or by value?

Ruby is neither passed by value nor pass by reference, at least not in the sense that those terms are used in C++ because everything in Ruby is an object. Ruby does something better described as "pass-by object reference."

Conclusion

In this article, we have extensively discussed the Method Arguments in ruby. We have discussed the positional arguments, variable length arguments, methods with no arguments, optional positional arguments, and the basic Introduction to Ruby. 

You can read/explore more articles on the topic of Ruby. Check out our blogs on Introduction to ruby on railsDirectory Structure in RubyRuby on Rails, and Ruby vs. Python. You can also refer to the Official Documentation and Ruby Koans. You can explore some more articles on For loop in RubyOperators in Ruby, or directly access the Coding Ninjas Studio for our courses.


Happy Coding!

Live masterclass