String interpolation in Ruby
Today I have struggled with one exercise from exercism.io. In the first look exercise was very simple: Write a function that greets the user by name, or by saying “Hello, World!” if no name is given. For an input of “Alice”, the response should be “Hello, Alice!”. If a name is not given, the response should be “Hello, World!”
.
On the first look, this task was very simple. To create some function that takes some argument instance variable. Below I passed the first resolution:
This solution is ok, but this is one little thing that can be changed to a proper more elegant solution. But first let thing what for is this line:
This line is instance variable and becomes class variable. Is this particular line is needed? I was thinking that yes, this line is needed, for me, this notation was more readable. But I was in mistake. This piece of code is useless. I can remove this line and execution this simple program will not change. Why? Variable:
that is in:
is interpolated inside the string, to get their value and not just referenced by their name to print on the screen. To wrap variable we can use:
So there is no need to create additional value and the final program code looks as follows:
Above code looks nicer that before. But why as a developer I should use string interpolation and what for? This code is very simple and short and probably someone can say why to use this type of construction? Let’s imagine some longer string that contains more than 5 or 6, maybe 122, or more variables. What then? Probably is more convenient to use this kind of string structure to make life easier. And the second thing: for me, the syntax is more readable and of a first look, it’s easier to figure out what’s going on in the code.
Reference:
- Ruby doc
- String interpolation - Wikipedia
- Why does string interpolation work in Ruby when there are no curly braces?
- String concatenation vs. interpolation in Ruby
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.