카테고리 없음

[Ruby] String to Array, capitalize ...

goakgoak 2019. 4. 6. 21:01

Converting a Ruby String to an Array

String은 split 메소드와 몇몇 정규식을 통해 배열로 변환할 수 있다.

  1. 전체 문자열을 배열로 만들기

    myArray = "ABCDEFGHIJKLMNOP".split
    => ["ABCDEFGHIJKLMNOP"]
  2. 문자열의 각각 문자를 배열 요소로 만들기 (feat. 정규식 '//'지정)

    myArray = "ABCDEFGHIJKLMNOP".split(//)
    => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"]
  3. 문자열을 공백으로 구분하여 배열 만들기

    myArray = "Paris in the Spring".split(/ /)
    => ["Paris", "in", "the", "Spring"]
  4. 문자열을 ,(콤마)로 구분하여 배열만들기

    myArray = "Red, Green, Blue, Indigo, Violet".split(/, /)
    => ["Red", "Green", "Blue", "Indigo", "Violet"]

Changing the Case of a Ruby String

capitalize와 captalize! 메소드를 사용해서 문자열의 첫번째 문자만 대문자로 바꿀 수 있다. capitalize는 수정된 메소드를 리턴하고 capitalize!는 문자열 자체를 바꾼다.

"paris in the spring".capitalize
=> "Paris in the spring"

upcase, downcase, swapcase

"PLEASE DON'T SHOUT!".downcase
=> "please don't shout!"

"speak up. i can't here you!".upcase
=> "SPEAK UP. I CAN'T HERE YOU!"

"What the Capital And Lower Case Letters Swap".swapcase
=> "wHAT THE cAPITAL aND lOWER cASE lETTERS sWAP"

출처

https://www.techotopia.com/index.php/Ruby_String_Conversions