How would I invoke the block to use _id.to_s
in ruby?
category_ids = categories.map(&:_id.to_s)
I am hacking it and doing the following right now:
category_ids = []
categories.each do |c|
category_ids << c.id.to_s
end
The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.
Method chaining is a convenient way to build up complex queries, which are then lazily executed when needed. Within the chain, a single object is updated and passed from one method to the next, until it's finally transformed into its output 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 map() 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.
You can pass a block to map and put your expression within the block. Each member of the enumerable will be yielded in succession to the block.
category_ids = categories.map {|c| c._id.to_s }
category_ids = categories.map(&:_id).map(&:to_s)
Test:
categories = ["sdkfjs","sdkfjs","drue"]
categories.map(&:object_id).map(&:to_s)
=> ["9576480", "9576300", "9576260"]
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