Skip to Content

compact_blank in Rails

Posted on

If you have an array or a hash, contains nil or empty element, and you want to remove them, we could use compact method:

[1, nil, 3, “”, []].compact
#=> [1, “3”, “”, []]

[1, nil, 3, “”, []].reject { |e| e.nil? || e&.empty? }
#=> [1, “3”]

[1, nil, 3, “”, []].reject(&:blank?)
#=> [1, “3”]

{1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.compact
#=> {1 => 2, “3” => “4”, 4 => “”, 5 => []}

{1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.reject { |_, v| v.nil? || v&.empty? }
#=> {1 => 2, “3” => “4”}

{1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.reject { |_, v| v.blank? }
#=> {1 => 2, “3” => “4”}

From Raisl 6.1, we can use compact_blank

[1, nil, 3, “”, []].compact_blank
#=> [1, “3”]

result = {1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.compact_blank
#=> {1 => 2, “3” => “4”}

References

comments powered by Disqus