Programing

줄 바꿈을 제거하지 않고 Ruby에서 여러 줄의 긴 문자열 나누기

lottogame 2020. 5. 1. 08:02
반응형

줄 바꿈을 제거하지 않고 Ruby에서 여러 줄의 긴 문자열 나누기


우리는 최근에 루비 스타일 가이드를 결정했습니다. 칙령 중 하나는 줄이 80자를 넘지 않아야한다는 것입니다. 이것이 Rails 프로젝트이기 때문에, 우리는 종종 약간 더 긴 문자열을 가지고 있습니다. 즉 " 사용자 X는 항상 80 자 스타일 제한에 맞지 않는 Thing Y에 대한 메시지를 보내려고했습니다 ."

긴 문자열이 여러 줄에 걸쳐있는 세 가지 방법이 있다는 것을 알고 있습니다.

  • 헤레 독
  • %큐{}
  • 실제 문자열 연결.

그러나이 모든 경우에 더 많은 계산주기가 걸리게되는데 이는 어리석은 것처럼 보입니다. 문자열 연결은 분명하지만, HEREDOC%Q같이 개행을 제거해야합니다 .gsub(/\n$/, '').

이것을 수행하는 순수한 구문 방법이 있습니까? 즉, 전체 문자열을 한 줄에 두는 것과 같습니다. 목표는 코드를 좀 더 읽기 쉽게하기 위해 추가주기를 사용하지 않는 것입니다. (예, 나는 당신이 그 절충을 많이해야한다는 것을 알고 있습니다 ... 그러나 문자열 길이에 대해서는 이것이 바보처럼 보입니다.)

업데이트 : 백 슬래시는 들여 쓰기를 잃어 버리기 때문에 원하는 스타일이 아닙니다. 스타일 / 가독성에 실제로 영향을 미칩니다.

예:

if foo
  string = "this is a \  
string that spans lines"  
end

위의 내용을 읽기가 어렵습니다.

편집 : 아래에 답변을 추가했습니다. 3 년 후 이제 우리는 구불 구불 한 이교도를 갖게되었습니다.


아마 이것이 당신이 찾고있는 것입니까?

string = "line #1"\
         "line #2"\
         "line #3"

p string # => "line #1line #2line #3"

\Ruby의 모든 라인이 다음 라인에서 계속됨을 나타내는 데 사용할 수 있습니다 . 이것은 문자열에서도 작동합니다.

string = "this is a \
string that spans lines"

puts string.inspect

출력합니다 "this is a string that spans lines"


3 년 후, Ruby 2.3에는 이제 해결책이 있습니다 : 구불 구불 한 heredoc.

class Subscription
  def warning_message
    <<~HEREDOC
      Subscription expiring soon!
      Your free trial will expire in #{days_until_expiration} days.
      Please update your billing information.
    HEREDOC
  end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be removed from each line of the content.


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.


I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:

%W[
  It's a nice day "#{name}"
  for a walk!
].join(' ')

where name = 'fred' this produces It's a nice day "fred" for a walk!

참고URL : https://stackoverflow.com/questions/10522414/breaking-up-long-strings-on-multiple-lines-in-ruby-without-stripping-newlines

반응형