1. Ruby 字符串(String)
'這是一個(gè) Ruby 程序的字符串'
puts "你好 #{name1}, #{name2} 在哪?"
# str 實(shí)例對象:可以調(diào)用任意可用的實(shí)例方法
myStr = String.new("THIS IS TEST")
# 字面量特殊語法
%q(this is a string) #same as: 'this is a string'
%Q|this is a string| #same as: "this is a string"
2. Ruby 數(shù)組
names = Array.new(20)
names = Array.new(4, "mac")
puts "#{names}"
結(jié)果:["mac", "mac", "mac", "mac"]
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"
結(jié)果:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]
digits = Array(0..9)
puts "#{digits}"
結(jié)果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# each 遍歷
# 數(shù)組內(nèi)建方法
Array.[](...) [or] Array[...] [or] [...]
# 字面量特殊語法
words = %w[this is a test] # same as: ['this','is','a','test']
open = %w| { [ < | # same as: ['{', '[', '<']
white = %W(\s \t \r) # same as: ["\s", "\t", "\r"]
# %w 開頭的遵循單引號引用規(guī)則 %W開頭遵循雙引號引用規(guī)則
3. Ruby 哈希
# 空的哈希
months = Hash.new
# 默認(rèn)值的哈希
months = Hash.new( "month" )
或
months = Hash.new "month"
# 有值的哈希
H = Hash["a" => 100, "b" => 200]
puts "#{H['a']}"
puts "#{H['b']}"
# 字面量特殊語法
numbers = {"one" => 1, "two" => 2}
作為哈希的鍵 symbol對象比字符串更高效
numbers = {:one => 1, :two => 2}
哈希的內(nèi)置方法
# 創(chuàng)建 Hash 對象實(shí)例
Hash[[key =>|, value]* ] or
Hash.new [or] Hash.new(obj) [or]
Hash.new { |hash, key| block }
4. Ruby 范圍
r = 'a'..'c' # begin <= x <= end
n = 'a'...'c' # begin <= x < end
r.each{|x| p x} # "a" "b" "c"
r.step(2){|x| p x} # "a" "c"
判斷是否包含在范圍
r = 0...100
r.member? 50 # true
r.include? 100 # false
r.include? 99.9 # true
ruby1.9 cover
triples = 'AAA'.."ZZZ"
triples.include? 'ABC'
triples.cover? 'ABCD'
5. Ruby 符號(symbol)
通過在一個(gè)標(biāo)識符或字符串前面添加冒號的方式表示一個(gè)符號字面量
:symbol
:"symbol"
:'another'
s = "string"
sym = :"#{s}"
# 字面量特殊語法-----%s
%s["] #same as: ' " '
反射代碼里判斷某個(gè)對象是否實(shí)現(xiàn)方法
# 判斷each
o.respond_to? :each
# eg:
> array
=> ["a", "b", "c"]
> str
=> "thiS iS a String"
2.3.4 :099 > str.respond_to?:each
=> false
2.3.4 :100 > array.respond_to?:each
=> true
2.3.4 :101 > name = :each
=> :each
2.3.4 :102 > array.respond_to?name
=> true
str和sym轉(zhuǎn)換
str = "string"
sym = str.to_sym
str = sym.to_s
6. Ruby True False Nil
true false nil 都是對象不是數(shù)值
true != 1
都是單鍵實(shí)例
條件判斷語句中 任何不同于false和nil的值表現(xiàn)的像true一樣包括數(shù)字0和1
nil和false表現(xiàn)的一樣
7. Ruby 對象
2.3.4 :116 > a=b="ruby"
=> "ruby"
2.3.4 :117 > c="ruby"
=> "ruby"
2.3.4 :118 > a.equal?b
=> true
2.3.4 :119 > a.equal?c
=> false
2.3.4 :120 > a == b
=> true
2.3.4 :121 > a == c
=> true
2.3.4 :122 > a.__id__
=> 70231259959460
2.3.4 :123 > b.__id__
=> 70231259959460
2.3.4 :124 > c.__id__
=> 70231259944360
對象的順序
2.3.4 :127 > 1<=>5
=> -1
2.3.4 :128 > 1<=>1
=> 0
2.3.4 :129 > 5<=>1
=> 1
2.3.4 :130 > 5<=>"1"
=> nil
2.3.4 :131 > "1"<=>"2"
=> -1