join用来合并字条串数组,可以接受0个或1个参数作为连接字符
注:0个参数时使用空字符进行连接。
["a", "b", "c"].join # => "abc"["a", "b", "c"].join(",") # => "a,b,c"
发现如果要把两个字符串连接在一起。如a = “abc”
b = a + “de”
此时b的值为”abcde”
但如果a = nil时,就会抛出未定义“+”的异常,因为此时a为nil。但如果我们改变一下b右边的表达式,将其改为b = “#{a}de”。这时就不会抛出错误了,此时b=>“de”。
向字符串末尾追加字符时, 使用 String#concat 或 <<运算符(String#<<)
s = 'abc'
s.concat('def')
p s #=>"abcdef"
s = 'abc'
s <<'def'
p s #=>"abcdef"
<<运算符还可以有以下的写
s = ''
s <<'abc' << 'def'
p s #=>"abcdef"