DEV Community

Cover image for How Ruby Macros Can Write Our Code For Us
Xauvkub Alex Yang
Xauvkub Alex Yang

Posted on

How Ruby Macros Can Write Our Code For Us

During my time at Flatiron Coding Bootcamp we've learned so much material in such short amount of time. More recently we've learned a language called Ruby. Using Ruby I've learned there's many things to make the coding process a lot faster and simpler. One way to do that is to use macros. A macro is like a method or set of instructions that writes your code for you. We use them a lot when using Active Record and they make the whole process a lot faster.

For example, I wrote a class instance getter and setter for a variable called name which took about six lines.

class Person
 def initialize(name)
    @name=name
 end

 def name
    @name
 end

 def name=(new_name)
    @name=new_name
 end
end
Enter fullscreen mode Exit fullscreen mode

But you could use a macro to write this much faster. To write our getter and setter methods we can use attr_writer and att_reader and assign them the symbol of name.

class Person
...
 attr_reader :name
 attr_writer :name
end
Enter fullscreen mode Exit fullscreen mode

That was much simpler! attr_writer created our setter method for us and att_reader created a getter method. But what's even better these two lines can actually be simplified to one line.

attr_accessor :name
Enter fullscreen mode Exit fullscreen mode

Macros are used so that we don't have to repeat writing the same actions over and over making work much simpler. It allows us to automate our tasks so that we don't have to spend more time remembering or writing some line of code. I'd highly recommend to research and use macros and shortcuts available to you to improve your productivity.

Top comments (0)