[Ruby] join & split

Nathan Lee
Change or Die!
Published in
2 min readJul 23, 2018

在處理字串( string ) 和陣列( array )之間轉換最常用到的就是 join 和 split 兩個方法。

join

用於將陣列( array )中的元素( element )轉成字串( string ),

[ "a", "b", "c" ].join=> "abc"[ "a", "b", "c" ].join("-")
=> "a-b-c"

split

用於將字串( string )轉成陣列( array ),

"a b c".split
=> ["a", "b", "c"]
"string".split(//)
=> ["s", "t", "r", "i", "n", "g"]
"hi mom".split(%r{\s*})
=> ["h", "i", "m", "o", "m"]
"now's the time".split(' ')
=> ["now's", "the", "time"]

--

--