简体   繁体   English

用空项替换数组中的每个项

[英]Replace every item in an array with an empty item

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 ] 例如,如果我有这个数组: [ 0, 5, 4, 7, 1 ]

I need to change it to: [ '', '', '', '', ''] 我需要将其更改为: [ '', '', '', '', '']

I'm using Ruby 1.9.3. 我正在使用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. 是的,跛脚。

Enumerable#map replaces every element with the result of calling a block: Enumerable#map用调用块的结果替换每个元素:

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! 如果你想变异原始(如果我明白你的问题这恰恰是你不想做什么),然后用#map!

array.map! { '' }
array
#=> ['', '', '', '', '']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM