2015-10-23 107 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 + /,'')'。 –