IT story

Ruby에서 문자열을 snake_case에서 CamelCase로 변환

hot-time 2020. 6. 3. 08:23
반응형

Ruby에서 문자열을 snake_case에서 CamelCase로 변환


뱀 케이스에서 낙타 케이스로 이름을 변환하려고합니다. 내장 된 방법이 있습니까?

예 : "app_user"~"AppUser"

(문자열 "app_user"을 모델로 변환하고 싶습니다 AppUser).


Rails를 사용하고 있다면 String # camelize 가 찾고 있습니다.

  "active_record".camelize                # => "ActiveRecord"
  "active_record".camelize(:lower)        # => "activeRecord"

실제 클래스를 얻으려면 그 위에 String # constantize사용해야 합니다.

"app_user".camelize.constantize

이건 어때?

"hello_world".split('_').collect(&:capitalize).join #=> "HelloWorld"

여기 주석에서 찾을 수 있습니다 : Ruby 문자열 분류

Wayne Conrad의 코멘트보기


사용하십시오 classify. 가장자리 케이스를 잘 처리합니다.

"app_user".classify # => AppUser
"user_links".classify   # => UserLink

노트 :

이 답변은 질문에 주어진 설명에만 해당됩니다 (질문 제목에만 국한되지는 않음). 문자열을 낙타 케이스로 변환하려고하면 Sergio 의 대답 을 사용해야합니다 . 질문자는 그가로 변환 app_user하고 AppUser싶지 않다고 App_user말했기 때문에이 대답은 ..


출처 : http://rubydoc.info/gems/extlib/0.9.15/String#camel_case-instance_method

학습 목적 :

class String
  def camel_case
    return self if self !~ /_/ && self =~ /[A-Z]+.*/
    split('_').map{|e| e.capitalize}.join
  end
end

"foo_bar".camel_case          #=> "FooBar"

lowerCase 변형의 경우 :

class String
  def camel_case_lower
    self.split('_').inject([]){ |buffer,e| buffer.push(buffer.empty? ? e : e.capitalize) }.join
  end
end

"foo_bar".camel_case_lower          #=> "fooBar"

순수한 루비 솔루션의 벤치 마크

순수한 루비 코드로 할 수있는 모든 가능성을 생각했습니다.

  • 대문자와 gsub

    "app_user".capitalize.gsub(/_(\w)/){$1.upcase}
    
  • &속기를 사용하여 분할 및 매핑 (user3869936의 답변 덕분에)

    "app_user".split('_').map(&:capitalize).join
    
  • 분할 및지도 (블랙 씨의 답변 덕분에)

    "app_user".split('_').map{|e| e.capitalize}.join
    

그리고 여기에이 모든 것들에 대한 벤치 마크가 있습니다. 나는 126 080 단어를 사용했습니다.

                              user     system      total        real
capitalize and gsub  :      0.360000   0.000000   0.360000 (  0.357472)
split and map, with &:      0.190000   0.000000   0.190000 (  0.189493)
split and map        :      0.170000   0.000000   0.170000 (  0.171859)

낙타 사건에서 뱀 사건으로가는 당신의 질문의 반대를 찾고 있습니다. 밑줄사용하십시오 (데 카멜 화하지 않음).

AppUser.name.underscore # => "app_user"

또는 이미 낙타 케이스 문자열이있는 경우 :

"AppUser".underscore # => "app_user"

또는 테이블 이름을 얻으려면 아마도 뱀 사례를 원할 것입니다.

AppUser.name.tableize # => "app_users"


여기에 더 많은 답변을 추가하는 것이 약간 불편하다고 느낍니다. @ ulysse-bn의 멋진 벤치 마크를 무시하고 가장 읽기 쉽고 최소한의 순수한 루비 접근법을 사용하기로 결정했습니다. :classmode는 @ user3869936의 복사본 이지만 :method다른 답변에서는 볼 수없는 모드입니다.

  def snake_to_camel_case(str, mode: :class)
    case mode
    when :class
      str.split('_').map(&:capitalize).join
    when :method
      str.split('_').inject { |m, p| m + p.capitalize }
    else
      raise "unknown mode #{mode.inspect}"
    end
  end

결과는 다음과 같습니다

[28] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :class)
=> "AsdDsaFds"
[29] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :method)
=> "asdDsaFds"

Most of the other methods listed here are Rails specific. If you want do do this with pure Ruby, the following is the most concise way I've come up with (thanks to @ulysse-bn for the suggested improvement)

x="this_should_be_camel_case"
x.gsub(/(?:_|^)(\w)/){$1.upcase}
    #=> "ThisShouldBeCamelCase"

Extend String to Add Camelize

In pure Ruby you could extend the string class using the exact same code from Rails .camelize

class String
  def camelize(uppercase_first_letter = true)
    string = self
    if uppercase_first_letter
      string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
    else
      string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
    end
    string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
  end
end

참고URL : https://stackoverflow.com/questions/9524457/converting-string-from-snake-case-to-camelcase-in-ruby

반응형