Shilpi Agrawal
Posted on September 20, 2020
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.
Dynamic Method Calls: If you want to call any dynamic method instead of writing if-else logic again and again.
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.
So, instead of writing like this in above code.
if word == "awful"
puts "Claw-ful"
elsif word == "perfect"
puts "Purr-fect"
end
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!
Posted on September 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 16, 2024
September 12, 2024