我有一个红宝石多维数组,如下所示:[[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]]
在红宝石中替换多维数组中的元素
我有点困惑,我该怎么做?
我有一个红宝石多维数组,如下所示:[[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]]
在红宝石中替换多维数组中的元素
我有点困惑,我该怎么做?
arr = [[a, b, c], [d, e, f], [g, h, i]]
就地:
arr.each { |a| a[1].delete! ' ' }
永恒:
arr.dup.each { |a| a[1].delete! ' ' }
arr = [[a, b, c], [d, e, f], [g, h, i]]
arr.map! do |el|
el[1].gsub!(/\s+/, "")
el
end
注意:这将改变你的原始数组,这可能是你不想要的东西。
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] }
由于海报明确要求使用空格字符类,所以我认为假设它们只替换空格字符并不安全。 – Drenmi
@Drenmi,实际上OP说:“我想删除空格......”,但是,正如你所说的那样,然后提供一个正则表达式来删除所有的空格。提到这一点很好,但我们不要狡辩读者:如果要删除空格,请将'b.delete('')'改为'b.gsub(/ \ s + /,'')'。 –
由于海报明确要求使用空白字符类,我不认为假设他们只替换空格字符是安全的。 – Drenmi
dup + each =地图 – Austio
@Austio这是错误的。 – mudasobwa