Programming

루비에서 첫 글자를 대문자로

procodes 2020. 7. 13. 22:00
반응형

루비에서 첫 글자를 대문자로


upcase방법은 전체 문자열을 대문자로 표시합니다.

첫 글자 만 대문자로 입력해야합니다.

또한 독일어와 러시아어와 같은 몇 가지 인기있는 언어를 지원해야합니다.

어떻게합니까?


사용하는 Ruby 버전에 따라 다릅니다.

루비 2.4 이상

이 버전의 루비는 유니 코드 케이스 매핑을 지원하기 때문에 작동 합니다.

"мария".capitalize #=> Мария

루비 2.3 이하

"maria".capitalize #=> "Maria"
"мария".capitalize #=> мария

문제는 단지 원하는 것을하지 않는 мария것입니다 Мария. 대신에 출력 합니다 .

Rails를 사용하는 경우 쉬운 해결 방법이 있습니다.

"мария".mb_chars.capitalize.to_s # requires ActiveSupport::Multibyte

일을한다.

그렇지 않으면 유니 코드을 설치하고 다음과 같이 사용해야합니다.

require 'unicode'

Unicode::capitalize("мария") #=> Мария

루비 1.8

우선, 코딩 마법 주석 을 사용해야합니다 .

#!/usr/bin/env ruby

puts "мария".capitalize

제공 invalid multibyte char (US-ASCII)하는 동안 :

#!/usr/bin/env ruby
#coding: utf-8

puts "мария".capitalize

오류없이 작동하지만 루비 2.3 이하를 참조하십시오 .


문자열의 첫 단어의 첫 글자를 대문자로

"kirk douglas".capitalize
#=> "Kirk douglas"

각 단어의 첫 글자를 대문자로

레일에서 :

"kirk douglas".titleize
=> "Kirk Douglas"

또는

"kirk_douglas".titleize
=> "Kirk Douglas"    

루비에서 :

"kirk douglas".split(/ |\_|\-/).map(&:capitalize).join(" ") 
#=> "Kirk Douglas"

레일 외부에 있지만 여전히 titleize 메소드를 사용하려고합니다.

require 'active_support/core_ext'
"kirk douglas".titleize #or capitalize

불행히도, 기계가 제대로 대문자 / 소문자 / 자본을 작성하는 것은 불가능합니다. 컴퓨터가 이해하기에는 너무 많은 상황 정보가 필요합니다.

루비의 이유 String클래스는 ASCII 문자에 대한 대문자를 지원은 적어도이 있기 때문에, 어느 정도 잘 정의.

"컨텍스트 정보"란 무엇을 의미합니까?

예를 들어, 대문자를 i올바르게 사용하려면 텍스트의 언어를 알아야합니다. 예를 들어 영어 에는 점이없는 i대문자 와 점이있는 I작은 대문자 i있습니다. 그러나 터키어는 점이없는 i자본 I, 점이있는 자본 İ, 점이 ı없는 작은 점, 점이있는 작은 네 가지가 i있습니다. 그래서 영어 'i'.upcase # => 'I'와 터키어로 'i'.upcase # => 'İ'. 'i'.upcase, 언어에 따라 두 가지 다른 결과를 반환 할 수 있기 때문에 언어를 몰라도 단어를 올바르게 대문자로 입력하는 것은 불가능합니다.

그러나 루비는 언어를 모르고 인코딩 만 알고 있습니다. 따라서 Ruby의 내장 기능으로 문자열을 올바르게 대문자로 지정할 수 없습니다.

It gets worse: even with knowing the language, it is sometimes impossible to do capitalization properly. For example, in German, 'Maße'.upcase # => 'MASSE' (Maße is the plural of Maß meaning measurement). However, 'Masse'.upcase # => 'MASSE' (meaning mass). So, what is 'MASSE'.capitalize? In other words: correctly capitalizing requires a full-blown Artificial Intelligence.

So, instead of sometimes giving the wrong answer, Ruby chooses to sometimes give no answer at all, which is why non-ASCII characters simply get ignored in downcase/upcase/capitalize operations. (Which of course also reads to wrong results, but at least it's easy to check.)


Well, just so we know how to capitalize only the first letter and leave the rest of them alone (because sometimes that is what is desired)...

['NASA', 'MHz', 'sputnik'].collect do |word|
  letters = word.split('')
  letters.first.upcase!
  letters.join
end

 => ["NASA", "MHz", "Sputnik"]

Calling #capitalize would result in ["Nasa", "Mhz", "Sputnik"]


As of Active Support and Rails 5.0.0.beta4 you can use one of both methods: String#upcase_first or ActiveSupport::Inflector#upcase_first. Check this blog post for more info.


Use capitalize. From the docs:

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

      "hello".capitalize    #=> "Hello"
      "HELLO".capitalize    #=> "Hello"
      "123ABC".capitalize   #=> "123abc"

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

Below is another way to capitalize each word in a string. \w doesn't match Cyrillic characters or Latin characters with diacritics but [[:word:]] does. upcase, downcase, capitalize, and swapcase didn't apply to non-ASCII characters until Ruby 2.4.0 which was released in 2016.

"aAa-BBB ä мария _a a_a".gsub(/\w+/,&:capitalize)
=> "Aaa-Bbb ä мария _a A_a"
"aAa-BBB ä мария _a a_a".gsub(/[[:word:]]+/,&:capitalize)
=> "Aaa-Bbb Ä Мария _a A_a"

[[:word:]] matches characters in these categories:

Ll (Letter, Lowercase)
Lu (Letter, Uppercase)
Lt (Letter, Titlecase)
Lo (Letter, Other)
Lm (Letter, Modifier)
Nd (Number, Decimal Digit)
Pc (Punctuation, Connector)

[[:word:]] matches all 10 of the characters in the "Punctuation, Connector" (Pc) category:

005F _ LOW LINE
203F ‿ UNDERTIE
2040 ⁀ CHARACTER TIE
2054 ⁔ INVERTED UNDERTIE
FE33 ︳ PRESENTATION FORM FOR VERTICAL LOW LINE
FE34 ︴ PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
FE4D ﹍ DASHED LOW LINE
FE4E ﹎ CENTRELINE LOW LINE
FE4F ﹏ WAVY LOW LINE
FF3F _ FULLWIDTH LOW LINE

This is another way to only convert the first character of a string to uppercase:

"striNG".sub(/./,&:upcase)
=> "StriNG"

참고URL : https://stackoverflow.com/questions/3724913/capitalize-first-letter-in-ruby

반응형