What is the most elegant way to concatenate strings in Ruby?

What is the most elegant way to concatenate strings in Ruby?

I currently have this line:

source = "#{ROOT_DIR}/" << project << "/App.config"

Is there a cleaner or more efficient way to achieve this? Also, what is the difference between << and + when using Ruby concat strings?

Using + for String Concatenation : In Ruby, you can concatenate strings using the + operator, which is simple and easy to understand:

source = ROOT_DIR + "/" + project + "/App.config"

This method is clean and readable, but keep in mind that + creates new string objects instead of modifying existing ones."

Using << for Better Performance: Both methods are great! However, if performance is a concern, the << operator is more efficient because it modifies the existing string instead of creating a new one:

source = ROOT_DIR.dup  # Ensures the original string isn’t modified
source << "/" << project << "/App.config"

Using << avoids unnecessary object allocations, which can be beneficial in loops or large-scale operations."

Using File.join for Path Handling: While + and << work fine, since you’re dealing with file paths, a more Ruby-idiomatic way is using File.join:

source = File.join(ROOT_DIR, project, "App.config")

This method automatically handles slashes (/) and ensures platform compatibility (especially useful if running on Windows vs. Linux)."