Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation in Ruby

I am looking for a more elegant way of concatenating strings in Ruby.

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 +?

like image 488
dagda1 Avatar asked Dec 18 '08 13:12

dagda1


1 Answers

You can do that in several ways:

  1. As you shown with << but that is not the usual way
  2. With string interpolation

    source = "#{ROOT_DIR}/#{project}/App.config" 
  3. 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.

like image 70
Keltia Avatar answered Oct 17 '22 05:10

Keltia