Badr Tazi
Badr Tazi

Reputation: 759

replacing elements in a multi-dimensional array in ruby

I have a multidimentional array in ruby, like so: [[a, b, c], [d, e, f], [g, h, i]] and I want to remove spaces in every second object of each array with this function .gsub!(/\s+/, ""). So it is basically like doing: [[a, b.gsub!(/\s+/, ""), c], [d, e.gsub!(/\s+/, ""), f], [g, h.gsub!(/\s+/, ""), i]]

I am a little bit confused, how can I do that ?

Upvotes: 0

Views: 65

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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"]] 

To mutate arr:

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

Upvotes: 2

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

Inplace:

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

Immutable:

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

Upvotes: 3

Hyung Cho
Hyung Cho

Reputation: 127

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

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

Note: This will mutate your original array, which might be something you don't want.

Upvotes: 0

Related Questions