Beginner question: What is a role of plus in front of a string in ruby?

Viewed 98

I have a code that looks like following

value = +"#{x}/part"
value << "/part2"

I understand that value would contain something like valueOfX/part/part2, but I don't understand why there is + in front of the string. I tried searching for it, but search engines are not very good at understanding what "plus in front of a string ruby" means. I also tried to run this in online ruby repl with no difference when + is added or not added.

So question is why may it be useful to have + like this?

1 Answers

If the string is frozen, then return duplicated mutable string.

If the string is not frozen, then return the string itself.

source: https://ruby-doc.org/core/String.html#method-i-2B-40

So in your case, since your string is not frozen, your code is equivalent to:

value = "#{x}/part"

EDIT:

As explained by @stefan in the comments, in Ruby 2.x, interpolated string were frozen with frozen_string_literal: true. So value = +"#{x}/part" is not equivalent to value = "#{x}/part". It's not the case anymore with Ruby 3.

Related