programing

쉼표로 구분 된 문자열을 배열로 어떻게 변환합니까?

nasanasas 2020. 11. 7. 10:11
반응형

쉼표로 구분 된 문자열을 배열로 어떻게 변환합니까?


Ruby에서 쉼표로 구분 된 문자열을 배열로 변환하는 방법이 있습니까? 예를 들어 다음과 같은 문자열이있는 경우 :

"one,two,three,four"

이와 같은 배열로 어떻게 변환합니까?

["one", "two", "three", "four"]

split방법을 사용하여 수행하십시오.

"one,two,three,four".split(',')
# ["one","two","three","four"]

선행 / 후행 공백을 무시하려면 다음을 사용하십시오.

"one , two , three , four".split(/\s*,\s*/)
# ["one", "two", "three", "four"]

여러 줄 (예 : CSV 파일)을 별도의 배열로 구문 분석하려면 :

require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]

require 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]

>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]

참고 URL : https://stackoverflow.com/questions/4847499/how-do-i-convert-a-comma-separated-string-into-an-array

반응형