DEV Community

loading...

How to use string interpolation in method calls to simplify Ruby code

Spencer Tweedy
・1 min read

Here’s a tiny trick I learned about recently that I thought might come in handy to other people.

I’m a new Ruby developer, so I’m not totally confident it’s a best practice, but I have run across a benchmark test on Stack Overflow that compared it favorably to other techniques.

Here it is: let’s say you have some code like this if statement.

scope = 'month'
date = Date.new(2020,04,30) # relies on Ruby Standard Library

if scope == 'day'
    date.next_day
elsif scope == 'month'
    date.next_month
elsif scope == 'year'
    date.next_year
end

You may already know that you can make the code easier to read by using a case switcher:

scope = 'month'
date = Date.new(2020,04,30)

case scope
when 'day'
    date.next_day
when 'month'
    date.next_month
when 'year'
    date.next_year
end

But there’s a way to simplify it even further, by interpolating a string—in this case the value of a variable named scope—directly into a method call.

scope = 'month'
date = Date.new(2020,04,30)

date.send("next_#{scope}") # make sure to use double quotes for interpolation

If you’re using this technique to call a method on an object that has public and private methods, you might want to consider using public_send instead:

scope = 'month'
date = Date.new(2020,04,30)

date.public_send("next_#{scope}")

That’s it!

Discussion (0)