Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Assignment in Ruby
2.1.
Lvalue and Rvalue
2.2.
Example
2.3.
Splat Operator
3.
Assigning to Attributes and Array Elements
4.
Frequently Asked Questions
4.1.
What is an assignment operator?
4.2.
How many different forms of assignment expressions are there in Ruby?
4.3.
What is Method?
4.4.
What is Method Invocation?
4.5.
What are getter and setter methods?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Assigning to Attributes and Array Elements in Ruby

Author Sanchit Kumar
0 upvote

Introduction

In Ruby, there are different forms of assignment expressions which are simple assignment, abbreviated assignment and parallel assignment, and concept related to assignment to variables, assignment to constants and assignment to attributes and array elements.

In fact, the Ruby shorthand for calling a method is assigning to attributes and array elements. 

Ruby assignment

This blog will discuss the concept of assignment and how assigning to attributes and array elements in ruby is done.

So, let's learn about this idea of assigning to attributes and array elements.

Assignment in Ruby

The assignment or simple assignment in ruby is done using the assignment operator '='. It involves one ‘lvalue’, the ‘=’ operator, and one ‘rvalue’. 

Lvalue and Rvalue

An ‘lvalue’ is something present on the left-hand side of an assignment operator.

Values on the right-hand side of an assignment operator are commonly referred to as ‘rvalues’.

Example

We will be going through how the assignment is done with examples:

s = 6 		# Setting the ‘lvalue s’ to the value 6
You can also try this code with Online Ruby Compiler
Run Code


An abbreviated assignment is an expression that modifies the value of a variable by performing another operation (like addition) on the variable's current value. Assignment operators like += and *=, which combine binary operators with an equal sign(=), are used in the abbreviated assignments:

For example:

s *= 6 		# Setting the lvalue ‘s’ to the value ‘s*6’
You can also try this code with Online Ruby Compiler
Run Code


Any assignment expression with more than one ‘rvalue’ or ‘lvalue’ is said to be performing a parallel assignment. Here's an example:

s, t, u, v = 2, 4, 5, 7 		# Setting ‘s’ to 2, ‘t’ to 4, ‘u’ to 5 and ‘v’ to 7
You can also try this code with Online Ruby Compiler
Run Code


These tasks are effectively completed in parallel, rather than sequentially. The following two lines, for example, are not the same:

s, t = t, s 		# Swaps the values of two variables in 'Parallel' 
s = t; t = s 		# Both variables have the same value in 'Sequence'
You can also try this code with Online Ruby Compiler
Run Code


Ruby makes an array to hold the ‘rvalues’ and assigns it to the ‘lvalue’ when there is only one ‘lvalue’ and more than one ‘rvalue’:

s = 2, 4, 5 		# s = [2, 4, 5] 
You can also try this code with Online Ruby Compiler
Run Code


We can put an asterisk '*' before the ‘lvalue’ but the meaning or return value of this assignment will not change.

If we want to prevent multiple ‘rvalues’ from being combined into a single array, use a comma after the ‘lvalue’. Even if there is no ‘lvalue’ after that comma, Ruby behaves as if there are multiple ‘lvalues’:

s, = 2, 4, 5 		# s = 2, here, all the other values are discarded 
You can also try this code with Online Ruby Compiler
Run Code


Ruby tries to expand the ‘rvalue’ into a list of values to assign when there are multiple ‘lvalues’ but only a single ‘rvalue’. When an array is used as the ‘rvalue’, Ruby expands the array so that each element has its own ‘rvalue’. Ruby calls the to_ary method if the ‘rvalue’ is not an array but instead implements one, then expands the array it returns:

s, t, u, v = [2, 4, 5, 7] 		# This is same as s, t, u, v = 2, 4, 5, 7
You can also try this code with Online Ruby Compiler
Run Code

Splat Operator

Asterisks before ‘rvalues’ indicate that they are arrays (or objects that resemble arrays) and that the values of each of their elements should be ‘rvalues’. Assigning values proceeds as previously described, with the array elements replacing the array in the original rvalue list:

s, t, u, v = 2, 4, *[5, 7] 		# This is same as s, t, u, v = 2, 4, 5, 7
You can also try this code with Online Ruby Compiler
Run Code


Splatted rvalues can be array, hash and range. Any ‘rvalue’ that defines the to_a method can be prefixed with a splat in general. Splattering can be applied to any enumerable object, including enumerators. When a splat is applied to an object that lacks the to_a method, no expansion occurs and the splat evaluates the object itself.

When a ‘lvalue’ is preceded by an asterisk, it indicates that any additional ‘rvalues’ should be placed in an array and assigned to this ‘lvalue’. The value associated with that ‘lvalue’ is always an array with zero, one, or more elements:

s, t, *u = 2, 4, 5, 7			# s = 2; t = 4; u = [5, 7]
s, t, *u = 2, 4, 5			# s = 2; t = 4; u = [5]
s, t, *u = 2, 4				# s = 2; t = 4; u = []
s, t, *u = 2				# s = 2; t = nil; u = []

*s, t, u = 2, 4, 5, 7			# s = [2, 4]; t = 5; u = 7
*s, t, u = 2, 4, 5			# s = [2]; t = 4; u = 5
*s, t, u = 2, 4				# s = []; t = 2; u = 4
*s, t, u = 2				# s = []; t = nil; u = 2
You can also try this code with Online Ruby Compiler
Run Code


Splats can appear on both sides of the parallel assignment expression:

s, t, u, *v = 2, 4, [5, 7, 9] 	# s = 2; t = 4; u = 5; v = [7, 9]
You can also try this code with Online Ruby Compiler
Run Code


In the circumstance that there are more ‘lvalues’ than ‘rvalues’ and there is no splat operator present, the first ‘rvalue’ is assigned to the first ‘lvalue’, the second ‘rvalue’ is assigned to the second ‘lvalue’, and so on until all of the ‘rvalues’ have been assigned. 

The remaining ‘lvalues’ are then assigned ‘nil’, overwriting any existing value for that ‘lvalue’:

s, t, u, v = 2, 4, 5 			# Setting ‘s’ to 2, ‘t’ to 4, ‘u’ to 5 and ‘v’ to ‘nil’
You can also try this code with Online Ruby Compiler
Run Code


If there are more ‘rvalues’ than ‘lvalues’ and no splat operator is used, ‘rvalues’ are assigned to each ‘lvalue’ in order, and the remaining ‘rvalues’ are discarded:

s, t, u = 2, 4, 5, 7 			# Setting ‘s’ to 2, ‘t’ to 4, ‘u’ to 5 and 7 is not assigned to any variable
You can also try this code with Online Ruby Compiler
Run Code


Now that we know what assignment is let us learn about assigning to attributes and array elements.

Assigning to Attributes and Array Elements

The Ruby analog of calling a method is assigning to attributes and array elements. Let's say that object ‘o’ has a method called ‘m=’. Here, the method name ends with an equals sign. Then, in an assignment expression, ‘o.m’ can be utilized as an ‘lvalue’.

Suppose, the value ‘v’ is assigned. Therefore, o.m = v

This assignment is converted by the Ruby interpreter into the following method invocation:

o.m=(v) 	# This looks like an assignment if we remove the parenthesis and add a space
You can also try this code with Online Ruby Compiler
Run Code


That is, the value ‘v’ is passed to the method 'm=', and this method can do anything with this value ‘v’. Typically, it verifies that the value is of the desired type and falls within the desired range before storing it in an object's instance variable.

A method called 'm' commonly goes along with methods like 'm=', and it just returns the value that was most recently supplied to 'm='.

  • 'm=' is a setter method.
  • 'm' is a getter method.
     

When an object has this setter and getter pair of methods, we say that the object has an attribute 'm'. Attributes are sometimes referred to as 'properties' in other languages.

Invoking a method is another way to give array elements values. If an object 'o' defines a method named '[]=' that expects two arguments, then the expression o[a] = b is executed as:

o.[]=(a,b)
You can also try this code with Online Ruby Compiler
Run Code


It is possible to index an object with two values between the square brackets if it has a '[]=' method that takes three inputs. 

In this instance, the following two expressions are equivalent:

o[a,b] = c
o.[]=(a,b,c)
You can also try this code with Online Ruby Compiler
Run Code


Check out this problem - Maximum Product Subarray

Frequently Asked Questions

What is an assignment operator?

The equal operator "=" is used in Ruby as an assignment operator. This is applicable for variables as well as objects because strings, floats, and integers are all objects in Ruby, and we're always assigning objects.

How many different forms of assignment expressions are there in Ruby?

There are three different forms of assignment expressions in Ruby which are simple assignment (x = 1), abbreviated assignment (x += 1) and parallel assignment (x,y,z = 1,2,3).

What is Method?

The method is a collection of expressions that returns a value. The def keyword is used to define methods. Method's return value is the value of the last expression evaluated in its body.

What is Method Invocation?

How a method is invoked within a program is referred to as method invocation. Since using parenthesis is optional in Ruby, calling a method is a simple process. When an invocation is contained within an expression that contains additional function calls or operators, the usage of parenthesis is crucial.

What are getter and setter methods?

The value of an instance variable is obtained using getter methods, whereas the value of an instance variable of a class is set using setter methods.

Conclusion

This article extensively discussed assigning attributes and array elements in Ruby. We started with a brief introduction about the assignment and learned how assigning attributes and array elements are done.

After reading about the assigning to attributes and array elements in Ruby, are you not feeling excited to read/explore more articles on the topics related to Ruby? Don't worry; Coding Ninjas has you covered. To learn, see History of RubyExpressions and Operators in RubyAbbreviated AssignmentParallel AssignmentDocumentation of RubyOfficial Ruby FAQ, and Learn Ruby with the Edgecase Ruby Koans.

Recommended problems -

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Thank you

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass