patternrubyCritical
String concatenation in Ruby
Viewed 0 times
stringconcatenationruby
Problem
I am looking for a more elegant way of concatenating strings in Ruby.
I have the following line:
Is there a nicer way of doing this?
And for that matter what is the difference between
I have the following line:
source = "#{ROOT_DIR}/" << project << "/App.config"Is there a nicer way of doing this?
And for that matter what is the difference between
<< and +?Solution
You can do that in several ways:
-
With string interpolation
-
with +
In the end, it is a matter of taste.
- As you shown with
-
With string interpolation
source = "#{ROOT_DIR}/#{project}/App.config"-
with +
source = "#{ROOT_DIR}/" + project + "/App.config"
The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.
When dealing with pathnames, you may want to use File.join` to avoid messing up with pathname separator.In the end, it is a matter of taste.
Code Snippets
source = "#{ROOT_DIR}/#{project}/App.config"source = "#{ROOT_DIR}/" + project + "/App.config"Context
Stack Overflow Q#377768, score: 627
Revisions (0)
No revisions yet.