String concatenation in Ruby

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

    I'd prefer using Pathname:

    require 'pathname' # pathname is in stdlib
    Pathname(ROOT_DIR) + project + 'App.config'
    

    about << and + from ruby docs:

    +: Returns a new String containing other_str concatenated to str

    <<: Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.

    so difference is in what becomes to first operand (<< makes changes in place, + returns new string so it is memory heavier) and what will be if first operand is Fixnum (<< will add as if it was character with code equal to that number, + will raise error)

    0 讨论(0)
  • 2020-11-28 01:56

    For your particular case you could also use Array#join when constructing file path type of string:

    string = [ROOT_DIR, project, 'App.config'].join('/')]
    

    This has a pleasant side effect of automatically converting different types to string:

    ['foo', :bar, 1].join('/')
    =>"foo/bar/1"
    
    0 讨论(0)
  • 2020-11-28 01:57

    If you are just concatenating paths you can use Ruby's own File.join method.

    source = File.join(ROOT_DIR, project, 'App.config')
    
    0 讨论(0)
  • 2020-11-28 01:59

    You can also use % as follows:

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

    This approach works with ' (single) quotation mark as well.

    0 讨论(0)
提交回复
热议问题