I have an array:
scores = [1, 2, 3, "", 4] And I want to remove all blank values. But when I run this:
puts scores.reject(&:empty?) I get an error:
undefined method `empty' for 1:Fixnum How can I remove values that are not integers from my array in a one step process? I am using Ruby 1.9.3.
When you want to remove nil elements from a Ruby array, you can use two methods: compact or compact! . They both remove nil elements, but compact! removes them permanently. In this shot, we will be talking about the compact!
Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.
To reject only nil would be:
array.compact
If you want to remove blank values, you should use blank?: (requires Rails / ActiveSupport)
scores.reject(&:blank?) #=> [1, 2, 3, 4] "", " ", false, nil, [], and {} are blank.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With