Table of contents
1.
Introduction
2.
Classes in Ruby
3.
Quick and Easy Mutable Classes
3.1.
Method 1 - Attribute accessor Method
3.2.
Method 2 - Using Struct
4.
Frequently Asked Questions
4.1.
Are strings mutable in Ruby?
4.2.
What is the usage of Struct in Ruby?
4.3.
What are arrays in Ruby?
4.4.
What are Class Instance Variables?
4.5.
What in Ruby is freeze?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Quick and Easy Mutable Classes in ruby

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby is an object-oriented language in the purest meaning possible because each value in the language behaves like (or is) an object. Each object represents a certain class.

Quick and Easy Mutable Classes in Ruby

An object responds to a set of methods that are defined by a class. Classes have the ability to extend, subclass, inherit, and override the methods of their superclass. Classes may also contain modules or inherit their methods from them.

So, in this article, firstly we will see Classes, and then we will come to know about mutable classes using two different methods which are using attribute accessor as well as using struct.

So, What are classes in Ruby?

Classes in Ruby

Class in Ruby is an object that specifies a template for building other objects. The methods that can be used in any instance of a class are defined by its classes. 
 

  • A method on a class is turned into an instance method when it is defined inside of it. 
  • Any subsequent instances of that class will have access to that method. 
  • When a new class is formed, an object of type Class is initialized and assigned to a global constant. 

 

To know more about classes you can also refer to this article- Lets Get Dive Deep into The Classes of Ruby and Object creation and initialization in Ruby.

Quick and Easy Mutable Classes

In simple terms, mutable means changeable. A mutable object is one whose state can be changed after it is created. Unlike numbers, booleans, and a few other types, most objects in Ruby are immutable. 

Quick and Easy Mutable Classes in Ruby

They are objects of a class that permit changes to the object's state in some way. 
We can make class mutable using two methods:=

Method 1 - Attribute accessor Method

Object methods are public by default in Ruby, while data is private. We use the attr_reader and attr writer to access and modify data.

The attr_accessor is a shortcut method when you need both attr_reader and attr_writer. Since both reading and writing data are common, the idiomatic method attr_accessor is quite very useful. Let’s see how this method can be implemented.

Attribute Accessor method in Ruby

Assume you want to access and change a variable in a Ruby object. Normally, you would define methods for reading and writing to the variable separately:
 

Example

class Ninja
  def lang
    @lang
  end

  def lang=(str)
    @lang = str
  end
end

 

All of the above, however, could be written in a more idiomatic manner using attr_accessor:

 

class Ninja
 attr_accessor :name
end
You can also try this code with Online Ruby Compiler
Run Code

Let us now take one example and actually modify the data: 

 

Implementation

class MutablePoint 
	def initialize(x,y); @x, @y = x, y; end 
	def x; @x; end # The getter method for @x 
	def y; @y; end # The getter method for @y 

	def x=(value) # The setter method for @x 
		@x = value 
	end 
	def y=(value) # The setter method for @y 
		@y = value 
	end 
end  

p = MutablePoint.new(1,1) 

puts "Before applying the setter method" 
puts p.x
puts p.y

# The setter method for @x 
p.x = 0 
# The setter method for @y
p.y = 0

puts "After applying the the setter method"
puts p.x
puts p.y

 

Output

output

 

In the above example, we have made a class MutablePoint. Using the getter method we defined two points. After that we have set the values using setter methods and we will get the results accordingly. 

 

Let us modify our code using attr_accessor method: 

 

Implementation

class MutablePoint 
   attr_accessor :x
   attr_accessor :y
end  
p = MutablePoint.new
p.x = 2
p.y = 4
puts p.x
puts p.y
You can also try this code with Online Ruby Compiler
Run Code

 

Output

output

Method 2 - Using Struct

If you want a class to be mutable, one more way to create it is using Struct. A struct is a tool that can be used to create mutable classes. A core Ruby class that produces additional classes is called Struct

An artificial data container is a structure. It is used to bundle and serve a set of information without any logic, unlike an object.

For each attribute that it includes, a pair of getter/setter methods are provided. This is comparable to the class's attr_accessor function.

The named fields you specify have accessor methods in these created classes. There are two methods for creating a new class with Struct.new. 

Let us have a look at them:

 

Struct.new("class_name", :x, :y)     # Creates new class Struct::class_name to be specified 
class_name = Struct.new(:x, :y)     # Creates new class, assigns to the class_name

 

Here is an example of naming classes using the struct method.

Once a class has been created with Struct.new, you can use it like any other class. Its new method will expect values for each of the named fields you specify, and its instance methods provide read and write accessors for those fields: 
 

Implementation

Point = Struct.new(:x, :y) 
p = Point.new(1,2) # => #<struct Point x=1, y=2>
puts p.x # => 1
puts p.y # => 2
puts p.x = 3 # => 3


Output

Let us see one more example: 
 

Implementation

Ninja = Struct.new(:ninja_id, :ninja_rank) do
	def info
		"The #{ninja_id} Ninja got the #{ninja_rank} rank."
	end
end
# creating object of struct
a = Ninja.new("26th", "3rd")
puts a.info 

puts a.ninja_id 
puts a.ninja_id = 37

 

Output

output

This was so simple! don’t you think?🤓

Now it’s time for the questions. Let us now move to FAQs.

FAQs

Frequently Asked Questions

Are strings mutable in Ruby?

Nevertheless, in Ruby, every string is mutable by default. With Ruby's upcoming major version, this will change. Ruby 3 won't arrive for several years, at which point all string literals will be by default immutable.

What is the usage of Struct in Ruby?

Struct is a compact way to use accessor methods to group together a number of attributes without creating an explicit class.

What are arrays in Ruby?

Ruby arrays can contain objects such as Strings, Integers, Fixnum, Hash, Symbols, and even other Arrays. Ruby arrays are less rigid than arrays in other programming languages.

What are Class Instance Variables?

Instance variables are accessible across all methods for any given instance or object. That is, instance variables vary from object to object. Instance variables are denoted by the at sign (@) and the variable name.

What in Ruby is freeze?

Ruby uses the freeze method to make sure that an object cannot be modified. This technique is excellent for producing immutable objects. If you try to edit an object that has called the freeze method, a runtime error will be thrown by the program.

Conclusion

In this article, we have extensively discussed Quick and Easy Mutable classes using two methods Attribute accessor and Struct. 

We hope that this article has helped you enhance your knowledge regarding classes of Ruby. If you would like to learn more, check out our articles on Tainting Objects in RubyObject References in RubyRuby-langmore-on-ruby-langruby-lang.faqrubykoans and  many more.   

nINJAS logo

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

Do upvote our blog to help other ninjas grow.

Happy Learning!

Live masterclass