Send method | Metaprogramming in ruby -4

Prateek vyas
2 min readFeb 22, 2023

--

Call your methods in a different way

send is one of the important method available for us to do metaprogramming. send() is an instance method of the Object class. It is used to pass message to object. The first argument is the message to the object we are going to send, which is the method name and remaining arguments act as a argument to that method.

Let’s see it in action

class Hello
def hello(*args)
puts 'Hello ' + args.join(' ')
end
end
h = Hello.new
h.send :hello, 'rubyist' #=> "Hello rubyist"

We can use send to DRY up our code. Which is the most basic requirement if you’re working on any project.

Let’s take another example

class Book
attr_accessor :title, :author, :length
end

book_info = { title: 'Metaprogramming in ruby', author: 'andrew richards', length: 290 }

book = Book.new


book.title = book_info[:title]
book.author = book_info[:author]
book.length = book_info[:length]

In the above example i have created a class Book and then i have assigned a value to its attributes title author length .

But the Question arises that if there manynumber of attributes needed to assigned. will we go with the same approach? Ofcourse we shouldn’t.

That’s where the send comes in. We can just create one method inside the Book class which will use the power of send to DRY up our code.

Let’s see how.

class Book
attr_accessor :title, :author, :length
end

book_info = { title: 'Metaprogramming in ruby', author: 'andrew richards', length: 290 }

book = Book.new

class Book
def assign_values(book_info)
book_info.each do |key, value|
send("#{key}=", value)
end
end
end
book.assign_values(book_info)
book # => #<Book:0x0000556eb20fa958 @title="Metaprogramming in ruby", @author="andrew richards", @length=290>

In the above code we just created a assign_values method which in turn calls the send method on book object. and the code will become like this while being executed.

self.title = "Metaprogramming in ruby"
self.author = "andrew richards"
self.length = 290

send(“#{k}=”, v) calls the method <attribute_name>= in the Object class.

So we just saw how metaprogramming techniques can be useful to DRY up the code.

Thanks for giving it a read!

Happy coding.

--

--

Prateek vyas
Prateek vyas

Written by Prateek vyas

Hello i am prateek vyas working as a ruby developer

No responses yet