我有一个数组:
scores = [1, 2, 3, "", 4]
我想删除所有的空值。但是当我运行以下代码时:
puts scores.reject(&:empty?)
我遇到一个错误:
undefined method `empty' for 1:Fixnum
我如何以一步操作从数组中移除非整数值?我正在使用Ruby 1.9.3。
只拒绝nil
将是:
array.compact
blank?
函数:(需要Rails / ActiveSupport库)scores.reject(&:blank?)
#=> [1, 2, 3, 4]
""
, " "
, false
, nil
, []
, 以及 {}
都是空值。
它非常简单:
scores.grep(Integer)
scores.grep(Integer){|x| x+1 }
如果您想执行相同的操作,但是您的数字是字符串,则会有奖励:
scores.grep(/\d+/){|x|x.to_i}
Integer
,而不是 Fixnum
。 - Stefannil
,那么可以这样做:scores.reject(&:nil?)
scores.select{|e| e.is_a? Integer}
# => [1, 2, 3, 4]
scores = [1, 2, 3, "", 4, nil]
scores.reject{|s| s.to_s == ''}
# => [1, 2, 3, 4]
scores.reject!{|x| x.to_s.empty?}
scores.select{|score| score.is_a? Fixnum}
或者,由于Fixnum继承自Integer,您也可以选择
scores.select{|score| score.is_a? Integer)
如果这样更具描述性,那就这样做。
数组和可枚举对象往往提供了许多完成同一件事情的方法。
&:empty?
可以用于哈希、数组和字符串,但不能用于数字。在 reject 中使用的方法必须对列表中的所有项目有效。因此,&:blank?
可以很好地工作。