0

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 ?

3 Answers 3

3
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! ' ' }
Sign up to request clarification or add additional context in comments.

6 Comments

Since the poster explicitly asks to use the whitespace character class, I don't think it's safe to assume they're only replacing space characters.
See my reply to @Drenmi in my answer.
@mudasobwa - meant that if you are want to do immutable, i.e. create a new object, map does the same thing.
@Austio there are tons of methods on Enumerable that are immutable. That fact does not make them doing the same thing as .dup.each.
@CarySwoveland the question is definitely not about gsub, but about doing operations on second elements of array items. That’s why I do not bother to add a comment on “use gsub if...”. I like your solution more than mine, because it lacks this nasty access by hard-coded index.
|
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"]] 

To mutate arr:

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

2 Comments

Since the poster explicitly asks to use the whitespace character class, I don't think it's safe to assume they're only replacing space characters.
@Drenmi, actually the OP said, "I want to remove spaces...", but then, as you noted,presents a regex that deletes all whitespace. It was good to mention that, but let's not quibble readers: change b.delete(' ') to b.gsub(/\s+/,'') if whitespace is to be removed.
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.