Nested array delete nil
来源:互联网 发布:c语言学生选课管理系统 编辑:程序博客网 时间:2024/05/29 15:10
I have nested array like this:
['foo', [nil], 'baz', ['bar'], nil, ['zoo']]
as elegantly remove nil
but leave empty arrays?*I expect to see:
I would do as below :
a = ['foo', [nil], 'baz', ['bar'], nil, ['zoo']]a.map { |e| e.is_a?(Array) ? e.compact : e }.compact# => ['foo', [], 'baz', ['bar'], ['zoo']]
Update:
a.map { |e| e.instance_of?(Array) ? e.compact : e }.compact
Try the code:
array = ['foo', [nil], 'baz', ['bar'], nil, ['zoo']]array.map! {|v| v.is_a?( Array ) && v.compact || v }.compact# => ["foo", [], "baz", ["bar"], ["zoo"]]
or more flexible:
array.map! {|v| v.respond_to?( :compact ) && v.compact || v }.compact# => ["foo", [], "baz", ["bar"], ["zoo"]]
or with trap:
array.map! {|v| v.compact rescue v }.compact# => ["foo", [], "baz", ["bar"], ["zoo"]]
0 0
- Nested array delete nil
- Array#delete
- JS array delete element
- Dictionary and Array value cannot be nil
- delete the element of array
- js array json copy delete ...
- nil
- nil
- Ruby remove nil values from array with .reject
- Elasticsearch : array of innner object vs. nested object
- how to sort array in ruby if i have nil object inside array?
- (Boolan)详解 C++ Operator new\delete、placement new\delete、Array new\delete
- hibernate+spring delete,saveorupdate,find的时候为什么报nested exception is org.hibernate.MappingException:
- how to remove nil and blank string in an array in Ruby
- Access nested array, where depth is unknown until runtime in Ruby
- nil Nil NULL NSNull
- NSNULL nil NULL Nil
- nil Nil NULL NSNul
- MyEclipse从数据库反向生成实体类之Hibernate方式 反向工程
- MSP430--UART模块
- Flash-使用变形面板制作花朵
- dovecot安装
- 编译安装pdo_mysql
- Nested array delete nil
- <细节>C++的常用IO格式功能
- sed工具使用
- 斐波那契数列
- 黑马程序员_NSDictionary
- 随笔
- nodejs has no method 'configure'
- 关于K&R代码风格中的大括号
- pcDuino点亮LED