String concatenation in Ruby

前端 未结 16 1184
青春惊慌失措
青春惊慌失措 2020-11-28 01:28

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

I have the following line:

source = \"#{ROOT_DIR}/\" << project <<          


        
16条回答
  •  甜味超标
    2020-11-28 01:37

    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.

提交回复
热议问题