Breaking up long strings on multiple lines in Ruby without stripping newlines

后端 未结 5 1988
心在旅途
心在旅途 2020-12-12 09:37

We recently decided at my job to a ruby style guide. One of the edicts is that no line should be wider than 80 characters. Since this is a Rails project, we often have strin

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 10:36

    I had this problem when I try to write a very long url, the following works.

    image_url = %w(
        http://minio.127.0.0.1.xip.io:9000/
        bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
        28ed3774-b234-4de2-9a11-7d657707f79c?
        X-Amz-Algorithm=AWS4-HMAC-SHA256&
        X-Amz-Credential=ABABABABABABABABA
        %2Fus-east-1%2Fs3%2Faws4_request&
        X-Amz-Date=20170702T000940Z&
        X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
        X-Amz-Signature=ABABABABABABABABABABAB
        ABABABABABABABABABABABABABABABABABABA
    ).join
    

    Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

    Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

提交回复
热议问题