Using "Send" for Methods in Ruby

From the archive — written 16 years ago. About old posts.

I’m putting this here because I might remember it the next time I need it if I blog it. I learned it a while back (thanks, Ed) and promptly forgot how to do it when I needed it today. After a lot of scrabbling around and half-remembering and pawing through Spotlight results that led nowhere, I came across an entry on Khaled alHabache’s blog that reminded me of what I was forgetting.

So, given an object “a” that represents an article in a database I keep to track analytics data, and given that it has these three attributes:

  • thirty_day_views

  • sixty_day_views

  • ninety_day_views

I need to check those attributes as I loop through the results of an Analytics report. Examples below are stripped down to get to the point:

My first great idea ever was to try something like:

intervals = ["thirty_day_views", "sixty_day_views", "ninety_day_views"]

intervals.each do |i|

	p a.i

end

But that doesn’t work because, well … duh. And a."{i}" … heh. No.

But with “send” I can do that:

intervals = ["thirty", "sixty", "ninety"]

intervals.each do |i|

	p a.send("{i}_day_views") 

end

Which is tidier than:

p a.thirty_day_views

p a.sixty_day_views

p a.ninety_day_views

At least, it’s tidier when there’s more going on than that simple example. In my working script I saved about 50 lines of code and made it a lot easier to fiddle with what was left behind since I don’t have to worry about making corrections to four separate blocks that do the exact same thing.

There. Noted and tagged.

#analytics #ruby

Drop a line about this.