2015-10-23 110 views
0

我有一個紅寶石多維數組,如下所示:[[a, b, c], [d, e, f], [g, h, i]]我想用這個函數.gsub!(/\s+/, "")刪除每個數組中每個第二個對象的空格。所以它基本上是這樣做的:[[a, b.gsub!(/\s+/, ""), c], [d, e.gsub!(/\s+/, ""), f], [g, h.gsub!(/\s+/, ""), i]]在紅寶石中替換多維數組中的元素

我有點困惑,我該怎麼做?

回答

3
arr = [[a, b, c], [d, e, f], [g, h, i]] 

就地:

arr.each { |a| a[1].delete! ' ' } 

永恆:

arr.dup.each { |a| a[1].delete! ' ' } 
+0

由於海報明確要求使用空白字符類,我不認爲假設他們只替換空格字符是安全的。 – Drenmi

+0

dup + each =地圖 – Austio

+1

@Austio這是錯誤的。 – mudasobwa

0
arr = [[a, b, c], [d, e, f], [g, h, i]] 

arr.map! do |el| 
    el[1].gsub!(/\s+/, "") 
    el 
end 

注意:這將改變你的原始數組,這可能是你不想要的東西。

2
arr = [["Now is", "the time for", "all"], 
     ["good", "people to come", "to", "the"], 
     ["aid of", "their bowling", "team"]] 

arr.map { |a,b,*c| [a, b.delete(' '), *c] } 
    #=> [["Now is", "thetimefor", "all"], 
    # ["good", "peopletocome", "to", "the"], 
    # ["aid of", "theirbowling", "team"]] 

變異arr

arr.map! { |a,b,*c| [a, b.delete(' '), *c] } 
+0

由於海報明確要求使用空格字符類,所以我認爲假設它們只替換空格字符並不安全。 – Drenmi

+1

@Drenmi,實際上OP說:「我想刪除空格......」,但是,正如你所說的那樣,然後提供一個正則表達式來刪除所有的空格。提到這一點很好,但我們不要狡辯讀者:如果要刪除空格,請將'b.delete('')'改爲'b.gsub(/ \ s + /,'')'。 –