Friday, March 20, 2009

map method is one of the best methods in rails

This methods will turns the symbol to proc.

Here is an example:

>> tcs = TemplateCompatibility.find :all, :select => "DISTINCT id, template_id"
=> [#"1", "id"=>"1"}>, #"2", "id"=>"2"}>, #"3", "id"=>"3"}>, #"4", "id"=>"4"}>, #"5", "id"=>"5"}>, #"6", "id"=>"6"}>, #"7", "id"=>"7"}>, #"4", "id"=>"8"}>]

If you want to extract a specific field from the above result set or an array, here in the above example i want to extract specifically template_id values, then we can use "map" method to get the values in a new array. Here is the syntax to use it with this example.

>> tcs.map(&:template_id)
=> [1, 2, 3, 4, 5, 6, 7, 4]

Enjoy Coding & hacking too!

No comments: