how to remove nil and blank string in an array in Ruby
来源:互联网 发布:日本av作品番号数据库 编辑:程序博客网 时间:2024/05/18 00:56
I am new to Ruby and stuck with this issue. Let's say I have an array like this:
arr = [1, 2, 's', nil, '', 'd']
and I want to remove nil and blank string from it, i.e. final array should be:
arr = [1, 2, 's', 'd']
I tried compact but it gives this:
arr.compact!arr #=> [1, 2, 's', '', 'd'] doesn't remove empty string.
I was wondering if there's a smart way of doing this in Ruby.
You could do this:
arr.reject { |e| e.to_s.empty? } #=> [1, 2, "s", "d"]
Note nil.to_s => ''
.
If arr
might contain another kind of empty object (e.g, array or hash) that you wish to keep, change e.to_s.empty?
to e.to_s == ''
0 0
- how to remove nil and blank string in an array in Ruby
- Understanding nil?, empty? and blank? in Ruby and Rails
- How to format strings in an array in ruby?
- how to sort array in ruby if i have nil object inside array?
- How to remove the duplicated value in a String array
- How to group anagrams in a string into an array
- How to gsub \ in ruby array?
- How to create this array in Ruby?
- How to sort an array in Ruby to a particular order?
- How to define an array in c#.
- How to initialize an array in C
- .nil? .empty? .blank? .present? in Ruby on Rails
- How to find number of a specific integer in an array of Fixnums ruby
- Converting a array to an array of ranges in ruby
- Matching Portions of A String to Elements of an Array in Ruby
- How to get array from string contained identical symbols in Ruby?
- How to get array from string contained identical symbols in Ruby?
- Ruby: Count unique elements and their occurences in an array
- HTML5 Canvas 旋转
- 设计模式学习笔记--迭代(Iterator)模式
- tomcat启动失败
- Android ViewGroup拦截触摸事件详解
- Select模型(PIPE)
- how to remove nil and blank string in an array in Ruby
- Android 分享功能,过滤掉不需要的组件,解决出现“Android系统“问题
- xcode工程的文件夹类型 folder References group
- 超越Administrator的权限
- 关于Handler、 Looper 、MessageQueue的认识
- 必须掌握的八个DOS命令
- Valid Parentheses
- PDU编码规则
- 个人感悟