DEV Community

Shilpi Agrawal
Shilpi Agrawal

Posted on • Edited on

send() in ruby to call dynamic methods

For newbies in Ruby or Rails programming you will find this method .send being used at many places. You will find many tutorials and blogs explaining what it does and when to use.

To get myself an idea what is it. I had to go through lot of them. So, anyone who is new to ruby or meta programming. I will tell you a straight away answer what is it.

.send() is a method in Ruby to call any method without knowing its name. In your day to day coding you will have mainly two usage of it.

  1. Dynamic Method Calls: If you want to call any dynamic method instead of writing if-else logic again and again.

  2. Private Method Calls: If you really really want to call a private method. Its been called private method for a reason. So, don't use it for hack around. Use it only when its really needed.

.send excepts first argument as method name and later if their is an argument to be passed to that method.

Alt Text

So, instead of writing like this in above code.

if word == "awful"
 puts "Claw-ful"
elsif word == "perfect"
 puts "Purr-fect"
end
Enter fullscreen mode Exit fullscreen mode

we can use the above code using .send. This is just short and simple code, but it might be useful when you have tidy if else logics in your code.

If you find it helpful. Don't forget to drop some loves and comments. Thanks!

Top comments (0)