Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

Contents

String

index (substring [,offset]) -> fixnum or nil

index (regexp [,offset]) -> fixnum or nil

문자열에서 substring를 찾는다. 정규표현식을 사용할 수도 있다. 발견하면 발견한 위치의 index 값을 반환한다. 발견하지 못했다면 nil을 반환한다.
"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

split (pattern=$;, [limit]) -> anArray

String을 구분자를 기준으로 나눈다. 결과값은 구분자로 분리된 문자열의 배열이다.

만약 pattern없이 split를 호출하면, 공백문자를 구분자로 설정한다. pattern은 (Regexp)정규표현식을 사용할 수 있다.

만약 limit를 사용하면, limit 개수만큼 만 split를 진행한다.

" now's  the time".split        #=> ["now's", "the", "time"]
" now's  the time".split(' ')   #=> ["now's", "the", "time"]
" now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//)               #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]

"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]

scan

문자열에서 패턴과 일치하는 모든 부분 문자열을 찾아서 배열로 반환한다.
a = 'cruel world'
a.scan(/\w+/)    # ["cruel", "world"]

sub (pattern, replacement) -> new_str

sub (pattern, hash) -> new_str

sub (pattern){|match| block} -> new_str

str에서 첫번째 발생한 pattern을 두번째 매개변수로 치환한다. pattern은 정규표현식으로 표현할 수 있다.
puts "hello".sub(/[aeiou]/, '*')
puts "hello".sub(/([aeiou])/, '<\1>')
puts "service.a.com".sub("com", "co.kr")

succ -> new_str

next -> new_str

문자열에 포함된 알파벳과 숫자를 증가 시킨다.
"abcd".succ        #=> "abce"
"THX1138".succ     #=> "THX1139"
"<<koala>>".succ   #=> "<<koalb>>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"

chomp(separator=$/) -> new_str

String str의 끝부분에 있는 캐리지리턴(\r)문자와 라인피드(\n)문자를 제거한 새로운 String를 반환한다. 매개변수를 입력할 경우, 매개변수에 입력한 String를 찾아서 제거한다.
"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"

사용 예

특정 패턴사이에 있는 문자열 가져오기

테스트에 사용할 문자열이다.
Content-Type: multipart/alternative; boundary=047d7bd9037c9c372204e0f68a9d
--047d7bd9037c9c372204e0f68a9d
나는 boundary 문자열인"047d7bd9037c9c372204e0f68a9d"을 가져오고 싶다. "boundary="과 "\n"사이의 문자열을 가져오면 되겠다. index 메서드를 이용한 코드다.
str =<<eof
Content-Type: multipart/alternative; boundary=047d7bd9037c9c372204e0f68a9d
--047d7bd9037c9c372204e0f68a9d
eof

boundstr = 'boundary='
start_p = str.index(boundstr)
end_p = str[start_p..-1].index("\n")
puts str[(start_p+boundstr.length)..(start_p+end_p)]

scan을 이용한 방법이다.

		

히스토리

  • 작성일 :
  • 수정일
    • : chomp 추가