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?