문자열의 첫 문자 만 대문자로하고 나머지는 그대로 두시겠습니까? (울타리)
Rails가 문자열의 첫 번째 문자를 대문자로하고 나머지는 그대로 두도록하려고합니다. "나는 뉴욕에서 왔어요"가 "뉴욕에서 왔어요"로 바뀌는 문제에 봉착했습니다.
첫 번째 캐릭터를 선택하려면 어떤 방법을 사용해야합니까?
감사
편집 : macek이 제안한 것을 구현하려고했지만 "정의되지 않은 메서드 '대문자 화'" 오류가 발생합니다. 코드는 대문자 줄없이 잘 작동합니다. 도와 주셔서 감사합니다!
def fixlistname!
self.title = self.title.lstrip + (title.ends_with?("...") ? "" : "...")
self.title[0] = self.title[0].capitalize
errors.add_to_base("Title must start with \"You know you...\"") unless self.title.starts_with? 'You know you'
end
편집 2 : 작동합니다. 도와 주셔서 감사합니다!
편집 3 : 잠깐, 아니 내가하지 않았다 ... 여기에 내 목록 모델에있는 것입니다.
def fixlistname!
self.title = self.title.lstrip + (title.ends_with?("...") ? "" : "...")
self.title.slice(0,1).capitalize + self.title.slice(1..-1)
errors.add_to_base("Title must start with \"You know you...\"") unless self.title.starts_with? 'You know you'
end
편집 4 : macek의 편집을 시도했지만 여전히 정의되지 않은 메서드 '대문자 화' " 오류가 발생합니다. 내가 뭘 잘못하고있을 수 있습니까?
def fixlistname!
self.title = title.lstrip
self.title += '...' unless title.ends_with?('...')
self.title[0] = title[0].capitalize
errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end
편집 5 : 이것은 이상합니다. 아래 줄을 사용하여 정의되지 않은 메서드 오류를 제거 할 수 있습니다. 문제는 첫 글자를 숫자로 바꾸는 것 같습니다. 예를 들어, 대신 활용의 예를 로 하면 , 상기 회전 Y를 (A121)로
self.title[0] = title[0].to_s.capitalize
Titleize는 모든 단어를 대문자로 표시합니다. 이 줄은 무거워 보이지만 변경된 유일한 문자가 첫 번째 문자임을 보장합니다.
new_string = string.slice(0,1).capitalize + string.slice(1..-1)
최신 정보:
irb(main):001:0> string = "i'm from New York..."
=> "i'm from New York..."
irb(main):002:0> new_string = string.slice(0,1).capitalize + string.slice(1..-1)
=> "I'm from New York..."
이렇게해야합니다.
title = "test test"
title[0] = title[0].capitalize
puts title # "Test test"
Humanize를 사용할 수 있습니다. 텍스트 줄에 밑줄이나 기타 대문자가 필요하지 않은 경우.
입력:
"i'm from New_York...".humanize
산출:
"I'm from new york..."
str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
현재 레일 5.0.0.beta4 새 사용할 수있는 String#upcase_first
방법을 또는 ActiveSupport::Inflector#upcase_first
그것을 할 수 있습니다. 자세한 내용은이 블로그 게시물 을 확인하세요 .
객체 지향 솔루션 :
class String
def capitalize_first_char
self.sub(/^(.)/) { $1.capitalize }
end
end
그런 다음 이렇게 할 수 있습니다.
"i'm from New York".capitalize_first_char
str.sub(/./, &:capitalize)
편집 2
나는 당신의 문제를 재현 할 수없는 것 같습니다. 계속해서이 기본 Ruby 스크립트를 실행하십시오. 찾고있는 정확한 출력을 생성하고 Rails는 이러한 모든 방법을 지원합니다. 어떤 종류의 입력에 문제가 있습니까?
#!/usr/bin/ruby
def fixlistname(title)
title = title.lstrip
title += '...' unless title =~ /\.{3}$/
title[0] = title[0].capitalize
raise 'Title must start with "You know you..."' unless title =~ /^You know you/
title
end
DATA.each do |title|
puts fixlistname(title)
end
__END__
you know you something WITH dots ...
you know you something WITHOUT the dots
you know you something with LEADING whitespace...
you know you something with whitespace BUT NO DOTS
this generates error because it doesn't start with you know you
산출
You know you something WITH dots ...
You know you something WITHOUT the dots...
You know you something with LEADING whitespace...
You know you something with whitespace BUT NO DOTS...
RuntimeError: Title must start with "You know you..."
편집하다
편집 내용에 따라 다음과 같이 시도 할 수 있습니다.
def fixlistname!
self.title = title.lstrip
self.title += '...' unless title.ends_with?('...')
self.title[0] = title[0].capitalize
errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end
실물
이것은 트릭을 할 것입니다
s = "i'm from New York"
s[0] = s[0].capitalize
#=> I'm from New York
String#capitalize
전체 문자열에서 사용하려고 할 때 I'm from new york
방법이 다음과 같기 때문에 보았습니다 .
첫 번째 문자가 대문자로 변환되고 나머지는 소문자로 변환 된 str 의 복사본을 반환합니다 .
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"
Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap
after a dup
to get an edited copy
'test'.dup.tap { |string| string[0] = string[0].upcase }
If and only if OP would want to do monkey patching on String object, then this can be used
class String
# Only capitalize first letter of a string
def capitalize_first
self.sub(/\S/, &:upcase)
end
end
Now use it:
"i live in New York".capitalize_first #=> I live in New York
An even shorter version could be:
s = "i'm from New York..."
s[0] = s.capitalize[0]
No-one's mentioned gsub, which lets you do this concisely.
string.gsub(/^([a-z])/) { $1.capitalize }
Example:
> 'caps lock must go'.gsub(/^(.)/) { $1.capitalize }
=> "Caps lock must go"
Perhaps the easiest way.
s = "test string"
s[0] = s[0].upcase
# => "Test string"
Note that if you need to deal with multi-byte characters, i.e. if you have to internationalize your site, the s[0] = ...
solution won't be adequate. This Stack Overflow question suggests using the unicode-util gem
Ruby 1.9: how can I properly upcase & downcase multibyte strings?
EDIT
Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:
s = s.mb_chars
s[0] = s.first.upcase
s.to_s
What about classify method on string ?
'somESTRIng'.classify
output:
#rails => 'SomESTRIng'
string = "i'm from New York"
string.split(/\s+/).each{ |word,i| word.capitalize! unless i > 0 }.join(' ')
# => I'm from New York
'IT박스' 카테고리의 다른 글
PHP에서 foreach없이 키와 값으로 배열을 내파하는 방법 (0) | 2020.08.21 |
---|---|
람다식이 대리자 형식이 아니므로 '문자열'형식으로 변환 할 수 없습니다. (0) | 2020.08.21 |
Java RegEx는 대소 문자를 구분하지 않습니까? (0) | 2020.08.21 |
angularjs 필터에 인수 전달 (0) | 2020.08.21 |
입력에 대해 프로그래밍 방식으로 onchange 이벤트를 강제하는 방법은 무엇입니까? (0) | 2020.08.20 |