讀《programming ruby》筆記 一 String

學習了一段時間的Ruby on Rails,用它做了一些小東西,開始是直接看的《Agile Web Development with Rails 2nd》雖然很多東西做出來了,但是依然有些不懂的地方,所以現在回過頭來好好看看Ruby的書。

在ruby中所有的事物都是對象,String也不例外,含有兩個同樣值的字符串其實是兩個object,

a = "string"
b = "string"
c = a

puts a.object_id
puts b.object_id
puts c.object_id
#輸出:
#
#21676710
#21676690
#21676710

 

字符串的連接

a ="hello,"
b ="world!"
puts a+b
puts a<<b
#輸出:
#hello,world!
#hello,world!

如上面的代碼示例,可以用 "+"和"<<"進行兩個字符串的連接。如果字符串太長在代碼裏需要換行可以用下面的方法:

a ="hello,\
       world!"
b ="hello,"\
  +"world!"
puts a
puts b
#輸出:
#hello,       world!
#hello,world!

 上面我們演示了在雙引號內和引號外的兩種換行連接方式,在這裏需要注意,第一種方法輸出的結果中"world"字符前面帶有空格,這是因爲在給a賦值時world前有空格,而第二行的格式是包含在引號內的。

 

雙引號和單引號的區別:

雙引號內支持更多的轉義字符 比如\n

a ="hello,\nworld!"
b ='hello,\nworld!'
puts a
puts b
#輸出:
#hello,
#world!
#hello,\nworld!

雙引號內還支持表達式

 

a = "jack"
puts "who is #{a}"

#輸出:
#who is jack

 表達式以#{expression}的形式插入雙引號內輸出表達式的值。

全局變量和類變量不需要{},如下:

$greeting = "Hello" # $greeting is a global variable
@name = "Prudence" # @name is an instance variable
puts "#$greeting, #@name"

#輸出:
#Hello, Prudence
 

正則表達式:

ruby支持perl 標準的正則表達式,使用符號=~

a = "php is programming language ,ruby too"
puts a if a=~/php.*ruby/ 
puts a=~/php ruby/ 

#輸出:
#php is programming language ,ruby too
#nil

 如果匹配成功則返回匹配的字符在字符串中的位置。

在ruby中還有一些全局變量可以方便的使用,$`返回匹配串前面的字符,$&返回匹配的字符串,$'返回匹配串後面的字符串。

 

def show_regexp(a, re)
  if a =~ re
    "#{$`}<<#{$&}>>#{$'}"
  else
    "no match"
  end
end

puts show_regexp('Fats Waller', /a/)
#輸出:
#F<<a>>ts Waller
 

 

 

 

 

 

 

 

 

發佈了10 篇原創文章 · 獲贊 0 · 訪問量 1989
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章