String concatenation in Ruby

前端 未结 16 1167
青春惊慌失措
青春惊慌失措 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:42

    Situation matters, for example:

    # this will not work
    output = ''
    
    Users.all.each do |user|
      output + "#{user.email}\n"
    end
    # the output will be ''
    puts output
    
    # this will do the job
    output = ''
    
    Users.all.each do |user|
      output << "#{user.email}\n"
    end
    # will get the desired output
    puts output
    

    In the first example, concatenating with + operator will not update the output object,however, in the second example, the << operator will update the output object with each iteration. So, for the above type of situation, << is better.

提交回复
热议问题