A big part of Ruby programming is based on making the programmer life’s easier and better. Macros in Ruby were created so programmers don’t write the same things over and over again. So what is a macro in Ruby?!
A macro in Ruby is a piece of code that is responsible for generating other code which could be a new instance method. In my previous blog post, I explained how to write Setter and Getter methods in Ruby. In this blog post, I will show you how you can use some macros that will generate getter or setter methods for you.
Macro for getter method
Let’s use the same Student class example from the last blog post:
class Student
def initialize(name)
@name = name
end
#getter method
def name
@name
end
end
Ruby provides a way to include this getter method instead of always having to repeat the same thing. Here is how to do so:
class Student
attr_reader :name #this replaces the getter method above
def initialize(name)
@name = name
end
end
You even can include many instance variables in the same line. Let’s say the student class has another instance variable, for example age.
class Student
attr_reader :name, :age #this replaces the getter method above
def initialize(name, age)
@name = name
@age = age
end
end
Macro for setter method
class Student
attr_writer :name, :age #this replaces the setter method bellow def initialize(name, age)
@name = name
@age = age
end
#No need for this anymore
#def name=(name)
# @name = name
#end
end
attr_reader
is a macro for getter methods and attr_writer
is a macro for setter methods. In some cases, you will need getter and setter methods for the same instance variable. That’s why there is another macro to do both at the same time. attr_accessor
is a macro for generating a getter and a setter method.
Macro for both
class Student
attr_accessor :name, :age def initialize(name, age)
@name = name
@age = age
end
end
There is much more than setter and getter macros in Ruby. For example, when declaring a “has many” relationship in Rails application, you would use has_many
macro. You can read more about it here.
Hope that helps you understand what macros are in Ruby programming. If you have anything you would like to add, please comment below!