Array
Define Arrays
-
字面值直接定义
a = [3.14, 'pie', 159]
-
创建一个 Array Object
ruby
b = Array.new
-
创建字符串数组的简便方式
ruby
a = %w(abc de fg hello world) # => ['abc', 'de', 'fg', 'hello', 'world']
Index Array
-
Array 可通过 [] 操作符,使用整数来索引。
ruby
a = [1,3,5,7,9] a[-1] # => 9 a[0] # => 1 a[-99] # => nil
-
使用 Range 来索引, 返回一个区间的数组值
ruby
a = ["one","two","three","four", "five"] a[2] # => "three" a[-2] # => "four" a[0..2] # => ["one", "two", "three"] a[0...2] # => ["one", "two"] a[-3..-1] # => ["three", "four","five"] a[1..-2] # => ["two", "three", "four"]
-
[start,count] 返回起点至距离起点一定距离区间内的数组织,起点处为距离1
ruby
a = [1,3,5,7,9] a[1,3] # => [3,5,7] a[3,1] # => [7] a[-3,2] # => [5,7] a[1,0] # => []
Set elements in Array
-
只改变一个元素的值
ruby
a = [1,3,5,7,9] a[1] = 'bat' # => [1, 'bat', 5, 7, 9] a[-3] = 'cat' # => [1, 'bat', 'cat', 7, 9] a[3] = [9, 8] # => [1, 'bat', 'cat', [9,8], 9] a[6] # => [1, 'bat', 'cat', [9,8],9 nil, 99]
-
改变数组中多个元素的值
ruby
a = [1,3,5,7,9] a[2,2] = 'cat' # => [1,3,'cat',9] a[2,0] = 'dog' # => [1,3,'dog','cat', 9] a[1,1] = [9,8,7] # => [1,9,8,7,'dog','cat',9] a[0..3] = [] # => ['dog','cat',9] a[5..6] = 99, 98 # => ['dog','cat',9,nil,nil,99,98]
Use array as stack and queue
-
Stack
ruby
stack = [] stack.push "red" stack.push "green" stack.push "blue" stack # => ["red", "green", "blue"] stack.pop # => "blue" stack.pop # => "green" stack.pop # => "red" stack # => []
-
Queue
ruby
queue = [] queue.push "red" queue.push "green" queue.shift # => red queue.shift # => green
Return first and last n
entries in array (but don't remove them)
ruby
array = [1,2,3,4,5,6,7,8,9] array.first(2) # => [1,2] array.last(2) # => [8,9]
Hash
Definition
Hash 里面存放的是键值对,可以通过键(key)来索引出值(value),与 Array 不同的是,Hash 的 key 可以是任意类型的。如:symbols, string, regular expressions 等。
- 一般书写方式
ruby
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
- 当 Key 为 symbol 时,可以有简写方式
ruby
h = { :dog => 'canine', :cat => 'feline', :donkey => 'asinine' } h = { dog: 'canine', cat: 'feline', donkey: 'asinine' }
取值,赋值
ruby
h = { dog: 'canine', cat: 'feline', donkey: 'asinine' } h[:dog] # => 'canine' h[:cat] = 'feline2' # => { dog: 'canine', cat: 'feline2', donkey: 'asinine' }