4

This is admittedly a bit of an odd issue, but I need to basically empty every item in an array (but keep the item itself).

For instance, if I have this array: [ 0, 5, 4, 7, 1 ]

I need to change it to: [ '', '', '', '', '']

I'm using Ruby 1.9.3.

Some charting software I'm using requires an array for labels and the only way to hide those labels is to make the corresponding items blank. Yes, lame.

2
  • 2
    Has to be an in-place operation? (note that you lose referential transparency on whatever method does that) Commented Jul 30, 2013 at 21:02
  • Can you clarify "but keep the item itself"? Do you mean "I want to return the result of performing the function on a variable without changing the value of the underlying variable"? If so, see my answer below! Commented Jul 30, 2013 at 21:04

1 Answer 1

5

Enumerable#map replaces every element with the result of calling a block:

array = [ 0, 5, 4, 7, 1 ]
array.map { '' }
#=> ['', '', '', '', '']

If you wanted to mutate the original (if I understand your question this is precisely what you do NOT want to do), then use #map!

array.map! { '' }
array
#=> ['', '', '', '', '']
Sign up to request clarification or add additional context in comments.

3 Comments

There's also Array.new(n, '') and Array.new(n) { '' } (which version you use depends on what's happening to the array). And there's always [''] * n (which suffers from the same problems as Array.new(n, '')).
Also [''] * n will produce an n element array with every element being ''. So [''] * array.count would give the same result (but is slightly less clean IMO).
Typical stackoverflow race condition ;)

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.