Ruby

How to interpolate a Ruby Symbol

One tricky part in terms of its syntax, is the interpolation of a Ruby Symbol. This minipost aims to demonstrate Ruby Symbol interpolation and also how to add a space between two seperate words on a Ruby symbol declaration.

Most of the times, we do use Ruby Symbols in our code of the form :test (where test, any name of your choice). Sometimes thought, we might want to use two seperate words to name our Symbol with a space in between them.

The following snippet, demonstrates how to use two seperate words with a space in between to declare a Ruby Symbol:

:"test symbol"

If you try the above Symbol declaration on your irb console, you will get the following:

irb(main):001:0> :"test symbol"
=> :"test symbol"

Furthermore, sometimes it is required to interpolate the Symbol name with a dynamic variable in our code. To do that, a Ruby Symbol declaration that allows interpolation could be defined as follows:

:"test_#{inter}"

The inter on the above Symbol is a variable that can be any string. If we try the Symbol interpolation in our irb console we can expect the following results:

irb(main):001:0> inter = "symbol"
=> "symbol"
irb(main):002:0> :"test_#{inter}"
=> :test_symbol

You can now easily interpolate your Ruby Symbol name and add spaces between the words you choose to form the Symbol name for your convenience, while enjoying all the benefits that Symbol offers compared to a plain Ruby String.

Read also the following