Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Arrays: select(), collect(), and map()

Tags:

arrays

ruby

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:

[] 
like image 934
ingalcala Avatar asked Mar 28 '12 20:03

ingalcala


People also ask

What is difference between map and collect in Ruby?

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.

What is the difference between select map and collect?

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.”

What does .map do in Ruby?

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.

What is collect method in Ruby?

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.


1 Answers

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

like image 84
Emily Avatar answered Oct 18 '22 10:10

Emily