반응형
Ruby-문자열에서 일부 문자를 선택하는 방법
예를 들어 문자열의 처음 100자를 선택하는 기능을 찾으려고합니다. PHP에는 substr 함수가 있습니다.
루비에도 비슷한 기능이 있나요?
시도 foo[0...100]하면 모든 범위가 가능합니다. 범위는 음수 일 수도 있습니다. 그것은되어 아니라 문서에 설명 된 루비.
[]-operator 사용 ( docs ) :
foo[0, 100] # Get 100 characters starting at position 0
foo[0..99] # Get all characters in index range 0 to 99 (inclusive!)
foo[0...100] # Get all characters in index range 0 to 100 (exclusive!)
사용 .slice방법 ( docs ) :
foo.slice(0, 100) # Get 100 characters starting at position 0
foo.slice(0...100) # Behaves the same as operator []
그리고 완전성을 위해 :
foo[0] # Returns the indexed character, the first in this case
foo[-100, 100] # Get 100 characters starting at position -100
# Negative indices are counted from the end of the string/array
# Caution: Negative indices are 1-based, the last element is -1
foo[-100..-1] # Get the last 100 characters in order
foo[-1..-100] # Get the last 100 characters in reverse order
foo[-100...foo.length] # No index for one beyond last character
Ruby 2.6 업데이트 : 이제 끝없는 범위 가 추가되었습니다 (2018-12-25 기준)!
foo[0..] # Get all chars starting at the first. Identical to foo[0..-1]
foo[-100..] # Get the last 100 characters
참고 URL : https://stackoverflow.com/questions/6423966/ruby-how-to-select-some-characters-from-string
반응형
'Program Club' 카테고리의 다른 글
| 루비에서 문자열을 숫자와 연결 (0) | 2020.11.16 |
|---|---|
| NSString을 설정된 길이로 자르려면 어떻게해야합니까? (0) | 2020.11.16 |
| ScrollView 내에서 스크롤 할 수없는 ListView (0) | 2020.11.16 |
| ASP.NET에 대한 이메일 주소 유효성 검사 (0) | 2020.11.16 |
| SQL Server에 null 값을 어떻게 삽입합니까? (0) | 2020.11.16 |