DEV Community

Spencer Tweedy
Spencer Tweedy

Posted on

2 1

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

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!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

DEV works best when you're signed in—unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay