Send keyword in Ruby

Recently I have been introduced to ruby, while working on the project I saw this function is been used many times in our existing codebase. Let’s discuss what problem it solves.

Consider you want to call a list of functions dynamically, eg. Consider an interaction to list animals data which takes the animal name as input

class AnimalController < ActiveInteraction
string :animal

 def execute
    if animal == 'cat'
       get_cat
    elsif animal == 'dog'
       get_dog
    end
 end
 
 def get_cat()
   # fetch cat
 end
 
 def get_dog()
   # fetch dog
 end
end

Here we are checking if the animal requested is cat or not. Send allow us to call the method taking method name as string

class AnimalController < ActiveInteraction
string :animal

 def execute
    send("get_"+animal)
 end
 
 def get_cat()
   # fetch cat
 end
 
 def get_dog()
   # fetch dog
 end
end

Send allow us to execute a method by just giving the name.

If you have knowledge about c# then you can relate this to reflection. Here it is simple. In c# it will be like

typeof(AnimalController).GetMethod("get_"+animal).Invoke(null)


Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *