[Ruby教學]String Class

字串是寫程式的時候很常遇到的資料型別之一,
我們先來看一些簡單的範例,了解Ruby的String class。

puts 'English words'     #English words

puts "中文字串"          #中文字串

puts "My name is 'Grady'"     #My name is 'Grady'

字串是使用單引號或雙引號包起來的內容。
差別在於,雙引號內可以使用一些特別的符號。
接下來介紹一些常用的方法。

#字串的長度
puts "A string".length         #8

#中文字串的長度
#String.size = String.length
puts "繁體中文".size           #8  註1

#連結字串物件
#使用 <<  +  concat 都是一樣的效果
puts "First" << "Second"     #FirstSecond
puts "Third" + "Fourth"      #ThirdFourth
puts "I" << "love" << "you"   #Iloveyou
puts "My".concat("name") << "is" + "Grady"     #MynameisGrady

#先設定一個字串物件
x = "this is test"

#取代文字
puts x.sub('test','not test')      #this is not test

#檢查是否為空
puts x.empty?     #false

#檢查是否包含字串或字元
puts x.include?('this')     #true

#分割字串,不加參數,效果和參數使用空白一樣,回傳值為陣列
puts x.split     #["this", "is", "test"]

#分割字串,使用空白字元當參數分割
puts x.split(' ')     #["this", "is", "test"]

#去除空白
y = " white space sentence "
puts y.strip     #"white space sentence"   去除兩邊空白
puts y.lstrip    #"white space sentence "  去除左邊空白
puts y.rstrip    #" white space sentence"  去除右邊空白

如果我們想把數字運算結果配合字串數出,有兩種方法,

puts "1 + 1 = " + 1 + 1
#會有錯誤訊息
#can't convert fixnum into String

#把fixnum轉為字串
puts "1 + 1 = " + (1 + 1).to_s     #1 + 1 = 2

#把運算式用#{}包起來
puts "1 + 1 = #{1 + 1}"     #1 + 1 = 2

#字串也可以轉為Fixnum
puts "123".to_i + 321     #444</pre>

另外還有幾個比較常用到的方法,請參看下面的程式碼。

#複制字串
#這裡的 * 是String提供的方法
puts "Here I am!" * 3     #Here I am!Here I am!Here I am!

#依照位置和長度取字元或字串 註2
#slice(開始的位置,要取字串的長度)
#需要注意的是,開始的位置是0
myDate = "20070123"
puts myDate.slice(0,4)     #2007 位置0開始,取長度四 (0,1,2,3)
puts myDate.slice(4,2)     #01 位置4開始,取長度二 (4,5)
puts myDate.slice(6,2)     #23 位置6開始,取長度二 (6,7)

#也可以用範圍
#slice(開始位置..結束位置)
puts myDate.slice(0..3)     #2007
puts myDate.slice(4..5)     #01
puts myDate.slice(6..7)     #23

String提供的方法還有很多,上面提到是比較基本的。

註1
用fxri執行的結果和在命令提示字元執行的結果不同。
我想是因為fxri編碼是使用Unicode,例如我輸入x = ‘繁體中文’
=> “\347\271\201\351\253\224\344\270\255\346\226\207″
所以fxir執行的結果是長度為12。

註2
由於字元編碼的關係,slice這個方法使用在中文上可能會得不到想要的結果。
Ruby目前(1.8.6)並沒有把字串設計為支援Unicode,
所以有些方法執行在不同編碼的字串可能會有不同的結果。
根據這篇文章,http://redhanded.hobix.com/inspect/futurismUnicodeInRuby.html
可以得知Ruby在版本1.9/2.0會有下列改變,
1.字元(character)由一個字的字串表示
2.所有String的方法將支位多位元(multibyte)字元
3.String會一個新方法,"encoding" (已經在1.9的文件中看到了)
4.IO也會有類似的方法,還有設定讀取資料編碼的方法(IO#encondig=)

[Ruby教學]String Class 有 “ 2 則留言 ”

發表留言