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"]
Question how about if I have:
irb(main):105:0> details[1] => {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
I want to delete every entry which has an empty qty value on this array or select only the ones with some value in it.
I tried:
details.map {|item|"" == item}
Just returns a lot of false and then when I use the same just change map to select I get:
[]
There's no difference, in fact map is implemented in C as rb_ary_collect and enum_collect (eg. there is a difference between map on an array and on any other enum, but no difference between map and collect ). Why do both map and collect exist in Ruby? The map function has many naming conventions in different languages.
The difference is super clear if you check the Ruby documentation: #collect: “Creates a new array containing the values returned by the block.” #select: “Returns a new array containing all elements of the array for which the given block returns a true value.”
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
The collect() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.
It looks like details
is an array of hashes. So item
inside of your block will be the whole hash. Therefore, to check the :qty
key, you'd do something like the following:
details.select{ |item| item[:qty] != "" }
That will give you all items where the :qty
key isn't an empty string.
official select documentation
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