在ruby中替换多维数组中的元素

时间:2015-10-23 16:45:18

标签: ruby

我在ruby中有一个multidimentional数组,如下所示:[[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 个答案:

答案 0 :(得分:3)

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

就地:

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

不可变:

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

答案 1 :(得分: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] }

答案 2 :(得分:0)

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

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

注意:这会改变您的原始数组,这可能是您不想要的。