<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Ruby 數組 > 原文: [https://zetcode.com/lang/rubytutorial/arrays/](https://zetcode.com/lang/rubytutorial/arrays/) 在 Ruby 教程的這一部分中,我們將介紹數組。 數組是對象的有序集合。 ## Ruby 數組定義 變量一次只能容納一項。 數組可以容納多個項目。 這些項目稱為數組的元素。 數組可以保存任何數據類型的對象。 每個元素都可以由索引引用。 數組從零開始。 第一個元素的索引為零。 請注意,Ruby 數組與 C,C++ 或 Java 之類的語言中的數組有很大不同。 ```ruby #!/usr/bin/ruby nums = [1, 2, 3, 4, 5] nums.each do |num| puts num end ``` 我們的第一個示例將創建一個包含五個整數的數組。 數組的元素將打印到控制臺。 ```ruby nums = [1, 2, 3, 4, 5] ``` 該行創建了一個由五個整數組成的數組。 元素之間用逗號分隔,并放在方括號之間。 ```ruby nums.each do |num| puts num end ``` 我們使用`each`方法遍歷數組,并將每個元素打印到控制臺。 ```ruby $ ./array.rb 1 2 3 4 5 ``` 這是程序的輸出。 ## Ruby 數組創建 Ruby 中的數組是一個對象。 數組可以用`new`方法實例化。 ```ruby #!/usr/bin/ruby nums = Array.new nums.push 1 nums.push 2 nums.push 3 nums.push 4 nums.push 5 puts nums ``` 在腳本中,我們首先創建一個`nums`數組。 然后,我們添加五個整數。 ```ruby nums = Array.new ``` 創建一個數組對象。 ```ruby nums.push 1 ``` `push`方法將一個項目附加到數組的末尾。 我們將繼續使用`new`方法創建數組對象。 ```ruby #!/usr/bin/ruby a1 = Array.new a2 = Array.new 3 a3 = Array.new 6, "coin" a4 = Array.new [11] a5 = Array.new (15) {|e| e*e} puts [a1, a2, a3, a4, a5].inspect ``` `Array`類的`new`方法可能有一些選項。 ```ruby a1 = Array.new ``` 創建一個空數組。 我們應該在以后用數據填充它。 ```ruby a2 = Array.new 3 ``` 在這里,我們創建了一個包含三個`nil`對象的數組。 ```ruby a3 = Array.new 6, "coin" ``` 創建一個包含六個`"coin"`字符串的數組。 第一個選項是數組的大小。 第二個選項是填充數組的對象。 ```ruby a4 = Array.new [11] ``` 第四個數組將具有一項。 ```ruby a5 = Array.new (15) {|e| e*e} ``` 我們創建一個包含 15 個元素的數組。 每個元素都在塊中創建。 在那里我們計算平方整數的序列。 ```ruby puts [a1, a2, a3, a4, a5].inspect ``` 我們將所有數組放入一個數組。 數組可以放入其他數組中。 然后我們在數組上調用`inspect`方法。 這將在所有元素上調用該方法。 `inspect`方法返回數組的字符串表示形式。 當我們需要快速檢查數組的內容時,這很有用。 ```ruby $ ./arraynew.rb [[], [nil, nil, nil], ["coin", "coin", "coin", "coin", "coin", "coin"], [11], [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196]] ``` 我們可以看到所有創建的數組的內容。 以下腳本顯示了在 Ruby 中創建數組的各種方法。 ```ruby #!/usr/bin/ruby integers = [1, 2, 3, 4, 5] animals = %w( donkey dog cat dolphin eagle ) weights = Array.new weights << 4.55 << 3.22 << 3.55 << 8.55 << 3.23 puts integers.inspect puts animals.inspect puts weights.inspect ``` 我們創建三個由整數,字符串和小數組成的數組。 ```ruby integers = [1, 2, 3, 4, 5] ``` 該行創建一個包含 5 個整數的數組。 這是經典的數組創建。 數組的元素放在方括號之間,并用逗號分隔。 ```ruby animals = %w( donkey dog cat dolphin eagle ) ``` 代碼行創建一個包含五個元素的字符串數組。 在這種模式下,我們保存一些輸入。 我們不使用逗號和雙引號。 ```ruby weights = Array.new weights << 4.55 << 3.22 << 3.55 << 8.55 << 3.23 ``` 在第三種方法中,有兩個步驟。 首先,我們創建一個`Array`對象,然后使用數據對其進行初始化。 這是一個正式的數組創建。 上述方式實際上是該表示法的簡寫。 ```ruby puts integers.inspect ``` `inspect`方法將數組的字符串表示形式打印到終端。 ```ruby $ ./creation.rb [1, 2, 3, 4, 5] ["donkey", "dog", "cat", "dolphin", "eagle"] [4.55, 3.22, 3.55, 8.55, 3.23] ``` 這是代碼示例的輸出。 數組項不限于數字和字符串。 數組可以包含所有 Ruby 數據類型。 ```ruby #!/usr/bin/ruby class Empty end nums = [1, 2, 3, 4, 5] various = [1, -1, "big", 3.4, Empty.new, nums, :two] puts various.inspect ``` 我們將各種 Ruby 對象放入各種數組中。 ```ruby various = [1, -1, "big", 3.4, Empty.new, nums, :two] ``` 該數組包含數字,字符串,自定義對象,另一個數組和符號。 ```ruby $ ./arrayobjects.rb [1, -1, "big", 3.4, #<Empty:0x987f704>, [1, 2, 3, 4, 5], :two] ``` 運行`arrayobjects.rb`示例,我們收到此輸出。 最后一個示例顯示了一個嵌套數組; 一個數組在另一個數組中。 在 Ruby 中,可以將數組嵌套到數組中。 ```ruby #!/usr/bin/ruby numbers = [1, 2, 3, [2, 4, 6, [11, 12]]] puts numbers.length puts numbers[0], numbers[1] puts numbers[3][0] puts numbers[3][1] puts numbers[3][3][0] puts numbers[3][3][1] puts numbers.flatten!.inspect ``` 數組`[11, 12]`嵌套在`[2, 4, 6, ...]`數組中,該數組也嵌套在`[1,2,3,...]`數組中。 ```ruby puts numbers.length ``` `length`方法返回 4。內部數組被計為一個元素。 ```ruby puts numbers[0], numbers[1] ``` 在這種情況下,`[]`字符用于訪問數組元素。 上面的行返回`numbers`數組的第一個和第二個元素(數字 1 和 2)。 方括號內的數字是數組的索引。 第一個索引為 0,返回第一個元素。 ```ruby puts numbers[3][0] puts numbers[3][1] ``` 在這里,我們從嵌套數組訪問元素。 `[3]`獲取第四個元素,即數組`[2, 4, 6, [11, 12]]`。 `[3][0]`返回內部數組的第一個元素,在本例中為 2。 `[3][1]`以類似的方式返回內部數組的第二個元素,即數字 4。 ```ruby puts numbers[3][3][0] puts numbers[3][3][1] ``` 現在我們更加深入。 我們訪問最里面的數組的元素。 `[3][3]`返回`[11, 12]`數組。 然后從該數組中獲得第一個(11)和第二個(12)元素。 ```ruby puts numbers.flatten!.inspect ``` `flatten!`方法拉平數組。 它從內部數組中獲取所有元素,并創建一個沒有任何內部數組的新元素。 ```ruby $ ./arrayofarrays.rb 4 1 2 2 4 11 12 [1, 2, 3, 2, 4, 6, 11, 12] ``` This is the output of the code example. ## Ruby 打印數組內容 常見的工作是將數組元素打印到控制臺。 我們有幾種方法可以完成此任務。 ```ruby #!/usr/bin/ruby integers = [1, 2, 3, 4, 5] puts integers puts integers.inspect integers.each do |e| puts e end ``` 在此腳本中,我們將數組的所有元素打印三次。 ```ruby puts integers ``` 將數組作為`puts`或`print`方法的參數是打印數組內容的最簡單方法。 每個元素都打印在單獨的行上。 ```ruby puts integers.inspect ``` 使用`inspect`方法,輸出更具可讀性。 該行將數組的字符串表示形式輸出到終端。 ```ruby integers.each do |e| puts e end ``` `each`方法為數組中的每個元素調用一次塊,并將該元素作為參數傳遞。 我們僅在每個元素上使用`puts`方法。 ```ruby $ ./printarray1.rb 1 2 3 4 5 [1, 2, 3, 4, 5] 1 2 3 4 5 ``` 該數組將打印到控制臺三遍。 在第二個示例中,我們提供了另外兩種打印數組元素的方式。 ```ruby #!/usr/bin/ruby integers = [1, 2, 3, 4, 5] integers.length.times do |idx| puts integers[idx] end integers.each_with_index do |num, idx| puts "value #{num} has index #{idx}" end ``` 在第一種情況下,我們使用`length`和`times`方法的組合。 在第二種情況下,我們使用`each_with_index`方法。 ```ruby integers.length.times do |idx| puts integers[idx] end ``` `length`方法返回數組的大小。 `times`方法迭代以下塊長度時間,將值從 0 傳遞到`length-1`。 這些數字用作有關數組的索引。 ```ruby integers.each_with_index do |num, idx| puts "value #{num} has index #{idx}" end ``` `each_with_index`迭代數組,并將元素及其索引傳遞到給定的塊。 這樣,我們可以輕松地一次打印元素及其索引。 ```ruby $ ./printarray2.rb 1 2 3 4 5 value 1 has index 0 value 2 has index 1 value 3 has index 2 value 4 has index 3 value 5 has index 4 ``` 這是示例的輸出。 ## Ruby 讀取數組元素 在本節中,我們將從數組中讀取數據。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h} puts lts.first puts lts.last puts lts.at(3) ``` 在第一個示例中,我們展示了三種簡單的數據檢索方法。 ```ruby puts lts.first puts lts.last ``` `first`方法讀取數組的第一個元素。 `last`方法讀取數組的最后一個元素。 ```ruby puts lts.at(3) ``` `at`方法返回具有特定索引的數組元素。 該行讀取數組的第四個元素。 ```ruby $ ./retrieval.rb a h d ``` 這是`retrieval.rb`程序的輸出。 `[]`字符可用于訪問數據。 這是許多其他編程語言所使用的訪問數組中數據的傳統方式。 它節省了一些打字。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h } puts lts[0] puts lts[-1] puts lts[0, 3].inspect puts lts[2..6].inspect puts lts[2...6].inspect ``` 我們展示了使用`[]`字符讀取數據的五個示例。 ```ruby puts lts[0] puts lts[-1] ``` 我們得到數組的第一項和最后一項。 我們將項目的索引號放在`[]`字符之間。 第一項的索引為 0,最后一項的索引為 -1。 ```ruby puts lts[0, 3].inspect ``` 當我們在方括號之間有兩個數字時,第一個是開始索引,第二個是長度。 在此代碼行中,我們從索引 0 開始返回 3 個元素。請注意`inspect`方法是可選的,僅用于產生更具可讀性的輸出。 ```ruby puts lts[2..6].inspect puts lts[2...6].inspect ``` 我們可以在方括號內使用范圍運算符。 在第一行中,我們從索引 2 到 6 讀取元素,在第二行中從 2 到 5 讀取元素。 接下來,我們將演示`values_at`方法。 此方法的優點是我們可以在`[]`字符之間放置多個索引以獲取各種元素。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h} puts lts.values_at(1..5).inspect puts lts.values_at(1, 3, 5).inspect puts lts.values_at(1, 3, 5, 6, 8).inspect puts lts.values_at(-1, -3).inspect ``` `values_at`方法返回一個數組,其中包含與給定選擇器相對應的元素。 `inspect`方法是可選的。 它用于獲取更具可讀性的輸出。 ```ruby puts lts.values_at(1..5).inspect ``` 此代碼行返回索引為 1 到 5 的元素。 ```ruby puts lts.values_at(1, 3, 5).inspect ``` 在這里,我們讀取索引為 1、3 和 5 的元素。 ```ruby puts lts.values_at(1, 3, 5, 6, 8).inspect ``` 我們放置了任意數量的索引。 如果沒有帶有特定索引的元素,則為零。 ```ruby puts lts.values_at(-1, -3).inspect ``` 負索引從數組末尾返回元素。 ```ruby $ ./retrieval3.rb ["b", "c", "d", "e", "f"] ["b", "d", "f"] ["b", "d", "f", "g", nil] ["h", "f"] ``` 這是腳本的輸出。 我們將使用`fetch`方法從數組讀取數據。 ```ruby #!/usr/bin/ruby lts = [0, 1, 2, 3, 4, 5, 6] puts lts.fetch(0) puts lts.fetch(-2) puts lts.fetch(8, 'undefined') puts lts.fetch(8) { |e| -2*e } ``` 我們展示了使用`fetch`方法的幾種形式。 ```ruby puts lts.fetch(0) puts lts.fetch(-2) ``` 第一行打印數組中的第一個元素。 第二行從數組末尾打印第二個元素。 ```ruby puts lts.fetch(8, 'undefined') ``` `fetch`方法的第三種形式返回具有給定索引的元素。 如果索引位于數組元素之外,則該方法返回默認值,在本例中為`"undefined"`。 如果沒有第二個參數,則`fetch`方法將引發`IndexError`。 ```ruby puts lts.fetch(8) { |e| -2*e } ``` 在`fetch`方法的最后一種形式中,我們有一個塊。 如果找不到具有給定索引的值,則該方法將返回調用該塊的值,并傳入索引。 ```ruby $ ./retrieval4.rb 0 5 undefined -16 ``` This is the output of the script. 我們將展示`take`和`take_while`方法的用法。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h} puts lts.take(4).inspect lts2 = lts.take_while { |e| e < 'f' } puts lts2.inspect ``` `take n`方法返回數組的前`n`個元素。 `take_while`方法將元素傳遞到塊,直到該塊返回`nil`或 false,然后停止迭代并返回所有先前元素的數組。 ```ruby puts lts.take(4).inspect ``` 在這里,我們返回數組的前四個元素。 ```ruby lts2 = lts.take_while { |e| e < 'f' } puts lts2.inspect ``` 在這里,我們從原始數組創建一個新數組。 在新數組中,所有字符都位于'f'字符之前。 ```ruby $ ./retrieval5.rb ["a", "b", "c", "d"] ["a", "b", "c", "d", "e"] ``` 在這里,我們看到`retrieval5.rb`程序的輸出。 `slice`方法與`[]`字符相同。 該方法從數組中返回一個或多個元素。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h} puts lts.slice(0) puts lts.slice(-1) puts lts.slice(0, 3).inspect puts lts.slice(2..6).inspect puts lts.slice(2...6).inspect ``` 我們介紹`slice`方法的五個示例。 ```ruby puts lts.slice(0) puts lts.slice(-1) ``` 這些`slice`方法的形式返回一個數組元素。 第一行代碼返回`lts`數組的最后一個元素,第二行返回。 ```ruby puts lts.slice(0, 3).inspect ``` 第一個參數是起始索引,第二個參數是長度。 在此代碼行中,我們從索引 0 開始返回 3 個元素。 ```ruby puts lts.slice(2..6).inspect puts lts.slice(2...6).inspect ``` 我們可以將范圍運算符與`slice`方法一起使用。 在第一行中,我們從索引 2 到 6 讀取元素,在第二行中從 2 到 5 讀取元素。 ```ruby $ ./retrieval6.rb a h ["a", "b", "c"] ["c", "d", "e", "f", "g"] ["c", "d", "e", "f"] ``` `slice`方法返回數組的一部分,數組的一個或多個元素。 可以從數組中選擇一個隨機數。 Ruby 為此具有`sample`方法。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h} puts lts.sample puts lts.sample(3).inspect ``` `sample`方法有兩種形式。 在第一種形式中,我們選擇一個隨機元素。 在第二種形式中,我們從數組中選擇 n 個隨機元素。 ```ruby $ ./random.rb b ["c", "f", "d"] $ ./random.rb d ["c", "d", "e"] ``` 兩次運行示例將得出不同的結果。 ## Ruby 數組操作 在以下示例中,我們將介紹幾種 Ruby 數組方法。 ```ruby #!/usr/bin/ruby num1 = [1, 2, 3, 4, 5] num2 = [6, 7, 8, 9, 10] puts num1 + num2 puts num1.concat num2 ``` 我們有兩個數組。 我們添加這兩個數組。 ```ruby puts num1 + num2 puts num1.concat num2 ``` 有兩種添加數組的方法。 我們可以使用+運算符或`concat`方法。 結果是一樣的。 Ruby 有很多使用數組的方法。 例如,`length`方法返回數組中的元素數。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f} puts lts.inspect puts "Array has #{lts.length} elements" puts "The first element is #{lts.first}" puts "The last element is #{lts.last}" puts lts.eql? lts.dup puts lts.eql? lts.dup.delete_at(0) lts.clear puts lts.inspect puts lts.empty? ``` 在上面的腳本中,我們介紹了七個新方法。 ```ruby puts "Array has #{lts.length} elements" ``` `length`方法確定數組的大小。 ```ruby puts "The first element is #{lts.first}" puts "The last element is #{lts.last}" ``` 在這里,我們獲得數組的第一個和最后一個元素。 ```ruby puts lts.eql? lts.dup ``` `eql?`方法確定兩個數組是否相等。 在我們的例子中,該行返回`true`。 `dup`方法創建對象的淺表副本。 它是從`Object`父級繼承的。 ```ruby puts lts.eql? lts.dup.delete_at(0) ``` `delete_at`方法刪除數組的第一個元素。 這次兩個數組不相等。 ```ruby lts.clear ``` `clear`方法從數組中刪除所有元素。 ```ruby puts lts.empty? ``` `empty?`方法檢查數組是否為空。 在我們的例子中,代碼行返回`true`,因為我們剛剛刪除了所有元素。 ```ruby $ ./basics.rb ["a", "b", "c", "d", "e", "f"] Array has 6 elements The first element is a The last element is f true false [] true ``` 這是示例的輸出。 一些 Ruby 數組方法以感嘆號結尾。 這是一個 Ruby 習慣用法。 感嘆號告訴程序員該方法將修改數據。 感嘆號本身沒有任何作用。 它只是一個命名約定。 ```ruby #!/usr/bin/ruby chars = %w{a b c d e} reversed_chars = chars.reverse puts reversed_chars.inspect puts chars.inspect reversed_chars = chars.reverse! puts reversed_chars.inspect puts chars.inspect ``` Ruby 除其他外,還有兩種相似的方法,即`reverse`方法和`reverse!`方法。 這兩種方法會更改元素的順序,并將它們顛倒過來。 不同之處在于`reverse`方法返回一個反向數組,并使原始數組保持原樣,而`reverse!`方法都修改了原始數組的內容。 ```ruby $ ./twotypes.rb ["e", "d", "c", "b", "a"] ["a", "b", "c", "d", "e"] ["e", "d", "c", "b", "a"] ["e", "d", "c", "b", "a"] ``` 我們可以清楚地看到前兩個數組是不同的。 第三和第四數組相同。 接下來的代碼示例中將介紹其他一些方法。 ```ruby #!/usr/bin/ruby numbers = [1, 2, 2, 2, 3, 4, 5, 8, 11] puts numbers.index 2 puts numbers.index 11 puts numbers.rindex 2 puts numbers.include? 3 puts numbers.include? 10 puts numbers.join '-' puts numbers.uniq!.inspect ``` 我們介紹了另外五種方法。 ```ruby puts numbers.index 2 puts numbers.index 11 ``` `index`方法返回數組元素的索引。 它從左邊返回第一個元素的索引。 第一行返回 1,它是數組中前 2 個的索引。 數組中只有 11 個,其索引為 8。 ```ruby puts numbers.rindex 2 ``` `rindex`從右邊返回第一個元素的索引。 在我們的例子中,最右邊的 2 具有索引 3。 ```ruby puts numbers.include? 3 puts numbers.include? 10 ``` `include?`方法檢查數組中是否存在元素。 第一行返回`true`; 3 存在。 第二行返回`false`; 我們的數組中沒有 10。 按照約定,以問號結尾的 Ruby 方法返回一個布爾值。 同樣,問號對數組沒有影響。 這只是對程序員的提示。 ```ruby puts numbers.join '-' ``` `join`方法返回由數組元素創建的字符串,由提供的分隔符分隔。 ```ruby puts numbers.uniq!.inspect ``` `uniq!`方法從數組中刪除重復的元素。 我們數組中的數字是 2 的三倍。 方法調用后,僅剩 1 個 2。 ```ruby $ ./methods2.rb 1 8 3 true false 1-2-2-2-3-4-5-8-11 [1, 2, 3, 4, 5, 8, 11] ``` 注意`join`方法的乘積。 它是一個字符串,其中數組的數字由`-`字符連接。 ## Ruby 修改數組 在本節中,我們將仔細研究修改數組的方法。 基本上,我們將對數組執行各種插入和刪除操作。 ```ruby #!/usr/bin/ruby lts = [] lts.insert 0, 'E', 'F', 'G' lts.push 'H' lts.push 'I', 'J', 'K' lts << 'L' << 'M' lts.unshift 'A', 'B', 'C' lts.insert(3, 'D') puts lts.inspect ``` 我們從一個空數組開始。 我們使用不同的插入方法來構建數組。 ```ruby lts.insert 0, 'E', 'F', 'G' ``` `insert`方法將三個元素插入`lts`數組。 第一個字母的索引為 0,第二個為 1,第三個為 3。 ```ruby lts.push 'H' lts.push 'I', 'J', 'K' ``` `push`方法將元素附加到數組。 我們可以附加一個或多個元素。 ```ruby lts << 'L' << 'M' ``` `<<`是`push`方法的同義詞。 它將元素添加到數組。 可以在鏈中調用此運算符/方法。 ```ruby lts.unshift 'A', 'B', 'C' ``` `unshift`方法將元素添加到數組的前面。 ```ruby lts.insert(3, 'D') ``` 在這種情況下,`insert`方法會在特定索引處插入`"D"`字符。 ```ruby $ ./insertion.rb ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"] ``` 使用上述數組插入方法,我們構建了此大寫字母數組。 有幾種刪除數組元素的方法。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g h} lts.pop lts.pop puts lts.inspect lts.shift lts.shift puts lts.inspect lts.delete_at(0) lts.delete('d') puts lts.inspect puts lts.clear puts lts.inspect ``` 在此腳本中,我們演示了從數組中刪除元素的五種方法。 ```ruby lts = %w{ a b c d e f g h} ``` 我們有 8 個元素組成的數組。 ```ruby lts.pop ``` `pop`方法從數組中刪除最后一個元素。 ```ruby lts.shift ``` `shift`方法從數組中刪除第一個元素。 ```ruby lts.delete_at(0) ``` `delete_at`刪除特定位置的元素。 我們刪除其余元素的第一個元素。 ```ruby puts lts.clear ``` `clear`方法清除數組中的所有元素。 ```ruby lts.delete('d') ``` `delete`方法從數組中刪除特定項目。 ```ruby $ ./deletion.rb ["a", "b", "c", "d", "e", "f"] ["c", "d", "e", "f"] ["e", "f"] [] ``` 在這里,我們看到了示例的輸出。 到目前為止,我們已經使用了方法(`clear`方法除外),這些方法通過一次添加或刪除項目來修改數組。 Ruby 的方法可以同時影響多個數組項。 ```ruby #!/usr/bin/ruby nms = [2, -1, -4, 0, 4, 3, -2, 3, 5] nms.delete_if { |x| x < 0 } puts nms.inspect ``` 該示例引入了`delete_if`方法,該方法刪除滿足塊中顯示的條件的所有項目。 ```ruby nms.delete_if { |x| x < 0 } ``` 此行從數組中刪除所有負數。 ```ruby $ ./delete_if.rb [2, 0, 4, 3, 3, 5] ``` 我們從`nms`數組中刪除了所有負數。 我們提出了另外兩種處理多個數組項的方法。 ```ruby #!/usr/bin/ruby lts = %w{ a b c d e f g} puts lts.inspect lts.reject! do |e| e =~ /[c-y]/ end puts lts.inspect lts.replace(["x", "y", "z"]) puts lts.inspect ``` 我們使用兩種方法,`reject!`方法和`replace`方法。 ```ruby lts.reject! do |e| e =~ /[c-y]/ end ``` `reject!`方法刪除塊內滿足特定條件的所有數組項。 就我們而言,我們刪除所有符合正則表達式的字母; 從`c`到`y`的任何字母。 `=~`運算符將字符串與正則表達式匹配。 ```ruby lts.replace(["x", "y", "z"]) ``` `replace`方法將用其他給定項目替換項目。 如有必要,它會截斷或擴展數組。 ```ruby $ ./modify.rb ["a", "b", "c", "d", "e", "f", "g"] ["a", "b"] ["x", "y", "z"] ``` 這是`modify.rb`示例的輸出。 ## Ruby 集操作 在本節中,我們介紹適用于 Ruby 數組的集操作。 在數學中,集合是不同對象的集合。 ```ruby #!/usr/bin/ruby A = [1, 2, 3, 4, 5] B = [4, 5, 6, 7, 8] union = A | B isect = A & B diff1 = A - B diff2 = B - A sdiff = (A - B) | (B - A) puts "Union of arrays: #{union}" puts "Intersection of arrays: #{isect}" puts "Difference of arrays A - B: #{diff1}" puts "Difference of arrays B - A: #{diff2}" puts "Symmetric difference of arrays: #{sdiff}" ``` 在上面的腳本中,我們演示了幾個集合操作,并集,交集,差和對稱差。 ```ruby nums1 = [1, 2, 3, 4, 5] nums2 = [4, 5, 6, 7, 8] ``` 我們定義兩個整數數組。 兩者都是集合,因為數組中的每個元素僅顯示一次。 這兩個數組有兩個共同的數字,即 4 和 5。 ```ruby union = nums1 | nums2 ``` 此操作是兩個數組的并集。 這兩個數組被添加。 最終數組中的每個元素僅顯示一次。 ```ruby isect = A & B ``` 以上操作是兩組的交集。 結果是具有兩個數組中都存在的元素的數組。 在我們的例子中,是 4 和 5。 ```ruby diff1 = A - B diff2 = B - A ``` 在這里,我們有兩個不同的運算,也稱為補數。 在第一行中,我們獲得 A 中存在但在 B 中不存在的所有元素。在第二行中,我們獲得屬于 B 而不是 A 的所有元素。 ```ruby sdiff = (A - B) | (B - A) ``` 在這里,我們有一個對稱的差異。 對稱差給出的元素要么在 A 要么在 B 中,但不在兩個集合中。 ```ruby $ ./setoperations.rb Union of arrays: [1, 2, 3, 4, 5, 6, 7, 8] Intersection of arrays: [4, 5] Difference of arrays A - B: [1, 2, 3] Difference of arrays B - A: [6, 7, 8] Symmetric difference of arrays: [1, 2, 3, 6, 7, 8] ``` This is the output of the example. ## Ruby 數組選擇,收集,映射方法 在下一個示例中,我們將介紹三種方法:`select`,`collect`和`map`方法。 ```ruby #!/usr/bin/ruby nums = [1, 3, 2, 6, 7, 12, 8, 15] selected = nums.select do |e| e > 10 end puts selected.inspect collected = nums.collect do |e| e < 10 end puts collected.inspect mapped = nums.map do |e| e*2 end puts mapped.inspect ``` 所有這些方法都對數組的元素執行批量操作。 ```ruby selected = nums.select do |e| e > 10 end ``` 在上面的代碼中,我們使用`select`方法創建一個新數組。 對于新創建的數組,我們選擇符合塊內條件的元素。 在我們的例子中,我們選擇所有大于 10 的元素。 ```ruby collected = nums.collect do |e| e < 10 end ``` `collect`方法的工作方式略有不同。 它為每個元素調用附加的塊,并從該塊返回值。 新數組包含`true`,`false`值。 ```ruby mapped = nums.map do |e| e*2 end ``` `map`方法的作用與`collect`方法相同。 在以上幾行中,我們從現有數組創建了一個新數組。 每個元素乘以 2。 ```ruby $ ./mass.rb [12, 15] [true, true, true, true, true, false, true, false] [2, 6, 4, 12, 14, 24, 16, 30] ``` 這些是新創建的數組。 ## Ruby 數組排序元素 最后,我們將對數組中的元素進行排序。 ```ruby #!/usr/bin/ruby planets = %w{ Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto } puts "#{planets.sort}" puts "#{planets.reverse}" puts "#{planets.shuffle}" ``` 該示例使用三種 Ruby 數組方法來重組數組中的元素。 ```ruby puts "#{planets.sort}" ``` `sort`方法按字母順序對數組元素進行排序。 ```ruby puts "#{planets.reverse}" ``` `reverse`方法返回一個新數組,其中所有元素的順序相反。 ```ruby puts "#{planets.shuffle}" ``` `shuffle`方法隨機重組數組元素。 ```ruby $ ./ordering.rb ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Pluto", "Saturn", ...] ["Pluto", "Neptune", "Uranus", "Saturn", "Jupiter", "Mars", "Earth", ...] ["Earth", "Jupiter", "Mercury", "Saturn", "Mars", "Venus", "Uranus", ...] ``` 這是代碼示例的示例輸出。 在本章中,我們使用了 Ruby 數組。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看