Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods and Parentheses in Ruby
2.1.
Required Parentheses
2.2.
Optional Parentheses
3.
Example for Methods and Parentheses in Ruby
3.1.
Output
4.
Frequently Asked Questions
4.1.
When should you use parentheses in Ruby?
4.2.
What is a method in Ruby?
4.3.
In Ruby, are parentheses required?
4.4.
In Ruby, what is a method call?
4.5.
What is the method missing in Ruby?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Methods and Parentheses in Ruby

Author Kanak Rana
0 upvote

Introduction

Do you know Ruby is a pure object-oriented programming language? Everything in Ruby is an Object.

Ruby introduction

Ruby is a dynamic, open source, object-oriented and reflective programming language. Ruby is considered similar to Perl and Smalltalk programming languages. It runs on all platforms like Windows, Mac OS, and all versions of UNIX.

Let's look into Methods and Parentheses in Ruby in detail

Methods and Parentheses in Ruby

Ruby's syntax is fundamentally based on methods, yet they are not actual values that programs may manipulate. Unlike texts, integers, and arrays, which are considered objects, Ruby's methods are not objects. 

Methods and Parentheses

However, it is possible to obtain a Method object that symbolizes a specific method, and we can indirectly activate methods by using Method objects. On the other hand, Parentheses can be avoided from most method invocations in Ruby. In most circumstances, this produces clean-looking code. However, it makes syntactic difficulties and puzzling corner cases in complex circumstances.

There are two types of parentheses.

  1. Optional Parentheses
  2. Required Parentheses

Required Parentheses

  • Some code is confusing if the parentheses are excluded, and Ruby requires them here. Nested method invocations(call) of forms f,g, x, and y are the most prevalent. 
     
  • In Ruby, invocations of that form are denoted by f(g(x,y)). However, Ruby 1.8 issues a warning since the code might alternatively be parsed as f(g(x),y). 
     
  • In Ruby 1.9, the warning was deleted. Use of the sum function, the following code prints 7 but generates a warning in Ruby 1.8.
     
puts sum 5,2

# To get rid of the warning, we will rewrite the code with parentheses around the arguments.
puts sum(5,2)
You can also try this code with Online Ruby Compiler
Run Code


It's worth noting that putting parentheses around the outer method call doesn't make the problem easier to solve.

puts(sum 5,2) 		# Does this mean puts(sum(5,2)) or puts(sum(5), 2)?
You can also try this code with Online Ruby Compiler
Run Code

 

  • When there is more than one parameter, an expression using nested function calls is unclear. 
  • Without parenthesis, Ruby does not attempt to understand what the code is trying to say in the following expressions!
     

For Example:

puts 8, sum 4,4    	# Error: does the second comma go with the 1st or 2nd method?
[sum 4,4]          	# Error: two array elements or one?
You can also try this code with Online Ruby Compiler
Run Code

 

  • Another complication emerges from the fact that parentheses are optional. When using parentheses in a method invocation, the opening parenthesis must come directly after the method name, with no space in between. 
     
  • This is because parentheses can be used to wrap an argument list in a method call and group expressions.
     

 Consider the two expressions below, which differ only by a single space:

square(3+3)*2    	# square(6)*2 = 36*2 = 72
square (3+3)*2  	# square(6*2) = square(12) = 144
You can also try this code with Online Ruby Compiler
Run Code

 

The parentheses in the first expression signify method invocation. They symbolize expression grouping in the second. To avoid misunderstanding, always put parentheses around a method invocation if any arguments are enclosed in parentheses. The second expression would be more clearly written as:

square(3+3)*2 

 

This parentheses conversation will conclude with one final twist. Remember that the following expression is confusing and should be avoided:

puts(sum 5,2) 		# Does this mean puts(sum(5,2)) or puts(sum(5), 2)?
You can also try this code with Online Ruby Compiler
Run Code

 

The best way to overcome this uncertainty is to surround the arguments to the sum method with parentheses. Another option is to insert a space between the put and the opening parenthesis:

puts (sum 5,2)
You can also try this code with Online Ruby Compiler
Run Code


By inserting a space, the method invocation parentheses are transformed into expression grouping parentheses. Since these parentheses group a subexpression, the comma can no longer be treated as an argument delimiter for the puts invocation.

Optional Parentheses

As the name says, In several basic Ruby codes, parentheses are excluded from method invocations. For example

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


In the first line, puts appears to be a built-in keyword, statement, or command. The comparable second line, with the parenthesis removed, reveals that it is just the call of a global method. Although the second form is more precise, the first is more concise, widely used, and, in some ways, more natural.

Consider the following code:

greeting = "Hello"
size = greeting.length
You can also try this code with Online Ruby Compiler
Run Code


If you're used to other object-oriented languages, you might think that string objects' length is a property, field, or variable. On the other hand, Ruby is purely object-oriented, and its objects are completely encased; the only way to interact with them is by calling their methods. “greeting.length” is a method call in this code. The length takes no parameters and is called without parentheses.

The code below is equivalent:

size = greeting.length()
You can also try this code with Online Ruby Compiler
Run Code

 

Optional parentheses highlight that a method calling (invoke) occurs.

The absence of parentheses in method invocations with no arguments creates the illusion of property access and is a widespread practice.

Parentheses are frequently omitted when the invoked method has zero or one argument. Even when there are numerous parameters, the parentheses may be removed, as shown in the following code:

x = 4
# x is a number
x.between? 1,5 		# Same as x.between?(1,5)
You can also try this code with Online Ruby Compiler
Run Code

 

In method definitions, parentheses may also be dropped around the argument list, though it is difficult to claim that this makes your code cleaner or more accessible. For example, the following code defines a method that returns the total of its arguments:

def sum a, b
   a+b 
end
You can also try this code with Online Ruby Compiler
Run Code

Check out this article - Balanced Parentheses, and Difference between argument and parameter.

Example for Methods and Parentheses in Ruby

We will be covering an example of methods and parentheses in Ruby for your better understanding. It is as follows:

# a and b are the parameters
def coding_Ninjas (a = "Welcome", b= "Ninjas")
     #  Statements to be executed
     puts "First parameter is #{a}"
     puts "First parameter is #{b}"
end

# Calling method with parameters
coding_Ninjas "Happy", "Learning"
puts ""
puts "Without Parameters"
puts ""

# Calling method without passing parameters
coding_Ninjas
You can also try this code with Online Ruby Compiler
Run Code

Output

Output for Methods and Parentheses in Ruby

Frequently Asked Questions

When should you use parentheses in Ruby?

Use parentheses for all method calls that take arguments, save for the methods puts and p (and later: require and include ) If a method does not accept any parameters, omit the empty parenthesis.

What is a method in Ruby?

In Ruby, a method is a collection of expressions that return a value.

In Ruby, are parentheses required?

Parentheses can be excluded from most method calls in Ruby. In most circumstances, this produces clean-looking code. However, it makes syntactic difficulties and puzzling corner cases in complex circumstances.

In Ruby, what is a method call?

The method is called (or invoked) by typing its name and giving parameters. In the method definition, you'll see a (words) following say. This is referred to as a parameter. Parameters are used when data exists outside the scope of a method description but needs to be accessed within the method specification.

What is the method missing in Ruby?

Method missing is a method in Ruby that allows you to manage scenarios you call a method that does not exist.

Conclusion

In this blog, we have learned about methods and parentheses in Ruby and the types of parentheses. You can look at the following link to know the methods and parentheses in Ruby in depth.

And other related articles are as follows:

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations.

Thank you

Do upvote our blog to help other ninjas grow. 

Happy Learning!

Live masterclass