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:

class HelloWorld
  def self.hello(name = "World")
    @name = name
    "Hello, #{@name}!"
  end
end

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:

@name = name

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:

name

that is in:

""Hello, #{name}!""

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:

#{name}

So there is no need to create additional value and the final program code looks as follows:

class HelloWorld
  def self.hello(name = "World")
    "Hello, #{name}!"
  end
end

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:

  1. Ruby doc
  2. String interpolation - Wikipedia
  3. Why does string interpolation work in Ruby when there are no curly braces?
  4. String concatenation vs. interpolation in Ruby

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee