Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i invoke a method chain using map method, in ruby?

Tags:

ruby

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
like image 474
Kamilski81 Avatar asked Feb 04 '13 15:02

Kamilski81


People also ask

How do you use the map method in Ruby?

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.

Can you chain methods in Ruby?

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.

Can you use map with hash 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 does .map return Ruby?

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.


2 Answers

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 }
like image 95
Winfield Avatar answered Oct 04 '22 03:10

Winfield


category_ids = categories.map(&:_id).map(&:to_s)

Test:

categories = ["sdkfjs","sdkfjs","drue"]
categories.map(&:object_id).map(&:to_s)
=> ["9576480", "9576300", "9576260"]
like image 30
megas Avatar answered Oct 04 '22 02:10

megas