What is the best way to filter an array in Ruby using select
, collect
, or map
?
I understand the syntax for mapping:
a = ["a", "b", "c", "d"] #=> ["a", "b", "c", "d"]
a.map { |item| "a" == item } #=> [true, false, false, false]
a.select { |item| "a" == item } #=> ["a"]
But if I have an array of hashes like this:
details[1]
=> { sku: "507772-B21", desc: "HP 1TB 3G SATA 7.2K RPM LFF (3 .", qty: "", qty2: "1", price: "5,204.34 P" }
How can I filter this array in Ruby to remove entries where qty
is an empty string or select only the ones that have a value?
I tried:
details.map { |item| "" == item }
But it just returns a lot of false
values. When I switch map
to select
, I get an empty array. What’s the correct approach to Ruby filtering in this case?
Using Select for Filtering: When working with an array of hashes in Ruby, select is a great way to filter out elements based on a condition.
Since you want to remove entries where qty is an empty string, you can do this:
filtered_details = details.select { |item| item[:qty] != "" }
This will return only those elements where qty is not an empty string. select is useful when you need to retain elements that meet a specific condition."
(Why map Doesn’t Work and Alternative Approach: You can also use map is not the right choice here because it transforms each element rather than filtering them.
details.map { |item| item[:qty] != "" }
=> [true, false, true, false] (Returns booleans, not filtered hashes)
To achieve filtering, reject is another alternative:
filtered_details = details.reject { |item| item[:qty] == "" }
While select keeps what matches the condition, reject removes what doesn’t. Sometimes reject makes the intention clearer when you want to exclude certain values."