RoR / Ruby 从嵌套数组中删除 nil 元素
要将数组分成两个相等的部分,我会这样做,
>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> a.in_groups_of( (a.size/2.0).ceil ) if a.size > 0
=> [[1, 2, 3], [4, 5, nil]]
现在我有一个嵌套数组,如果数组的大小是奇数,则它包含 nil 元素。如何从嵌套数组中删除 nil 元素?我想做类似的事情,
a.compact
但不幸的是,这不起作用,ruby 只删除第一级的 nil 元素,而不是递归地删除。 ruby 是否为这个问题提供了一些好的解决方案?
To split an array into two equal pieces I would do this,
>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> a.in_groups_of( (a.size/2.0).ceil ) if a.size > 0
=> [[1, 2, 3], [4, 5, nil]]
Now I've got a nested array that contains nil elements if the size of the array is odd. How can I remove the nil elements from the nested arrays? I want to do something like,
a.compact
But unfortunately that doesn't work, ruby only removes nil elements on the first level and not recursively. Does ruby provide any nice solutions for this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 Ruby 1.8.7 及更高版本,您可以执行以下操作:
使用 Ruby 1.8.6,您必须这样做:
这两者都会修改
a
的内容。如果您想返回一个新数组并保留原始数组,可以使用collect
而不是each
:With Ruby 1.8.7 and later you can do the following:
With Ruby 1.8.6, you have do do this the long way:
Both of these will modify the contents of
a
. If you want to return a new array and leave the original alone, you can usecollect
instead ofeach
:如果您要使用
in_groups_of
< /a> 您可以将其false
作为第二个参数传递,它不会用nil
填充“空白”,但实际上什么也没有。If you were to use the
in_groups_of
you can pass itfalse
as the second argument and it will not fill in the "blanks" withnil
, but truly nothing.除非您想永久更改a
Unless you want to permanently change a
应该工作....
Should work....