【讀書筆記】Ruby 中的 Array 和 Hash

Array

Define Arrays

  • 字面值直接定義express

    a = [3.14, 'pie', 159]
  • 建立一個 Array Object數組

    rubyb = Array.new
  • 建立字符串數組的簡便方式ruby

    rubya = %w(abc de fg hello world) # => ['abc', 'de', 'fg', 'hello', 'world']

Index Array

  • Array 可經過 [] 操做符,使用整數來索引。spa

    圖片描述

    rubya = [1,3,5,7,9]
    a[-1]    # => 9
    a[0]     # => 1
    a[-99]   # => nil
  • 使用 Range 來索引, 返回一個區間的數組值code

    rubya = ["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] 返回起點至距離起點必定距離區間內的數組織,起點處爲距離1blog

    rubya = [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

  • 只改變一個元素的值索引

    rubya = [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]
  • 改變數組中多個元素的值three

    rubya = [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圖片

    rubystack = []
    stack.push "red"
    stack.push "green"
    stack.push "blue"
    stack            # => ["red", "green", "blue"]
    
    stack.pop        # => "blue"
    stack.pop        # => "green"
    stack.pop        # => "red"
    stack            # => []
  • Queueelement

    rubyqueue = []
    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)

rubyarray = [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 等。

  • 通常書寫方式
rubyh = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine'  }
  • 當 Key 爲 symbol 時,能夠有簡寫方式
rubyh = { :dog => 'canine', :cat => 'feline', :donkey => 'asinine' }

h = { dog: 'canine', cat: 'feline', donkey: 'asinine' }

取值,賦值

rubyh = { dog: 'canine', cat: 'feline', donkey: 'asinine' }

h[:dog]             # => 'canine'
h[:cat] = 'feline2' # => { dog: 'canine', cat: 'feline2', donkey: 'asinine'  }
相關文章
相關標籤/搜索