The Ruby Array Map Method with examples

Akhilesh Sharma
May 16, 2019 · 2 min read

Hi folks, we use arrays as a data structure in almost all languages. Small arrays are very easy to create,destroy and can be very easily used to transform and manipulate data with single liners with no hassle of having to code complete implementations for memory management.(Arrays can be pretty complex too)

Now to modify the values of an array many languages use a very familiar method Map. Some of the earliest use of Map is with functional programming languages like Lisp(maplist). The concept of a map is not limited to lists or arrays ,however it works for abstract containers such as futures and promises(javascript) or with hashes(ruby).

In ruby map method takes an enumerable object( to be iterated upon) and a code block(ruby code block syntax {} or begin end), and runs the block for each element, adds the result of each iteration to a new array.

Taking some examples of use of map in ruby

The basic concept is take elements one by one send it to the code block(chunk of code), where one can modify data(like called add one in the example above) and let that method return some value for each element and add it to another array which is returned after all the iterations.

This covers the very basic use of arrays in Ruby.

Btw if you want to check the C code for map

From: array.c (C Method):Owner: ArrayVisibility: publicNumber of lines: 13static VALUErb_ary_collect(VALUE ary){long i;VALUE collect;RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);collect = rb_ary_new2(RARRAY_LEN(ary));for (i = 0; i < RARRAY_LEN(ary); i++) {rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));}return collect;}

If you have used the map method in other languages as well or want to use it below is a link you can refer to, for easy links to documentation in python,ruby and javascript.

http://www.spors.in/users/akhileshsharma.akisTV/properties/5cdd7d5d0093250022475757

Akhilesh Sharma

Written by

Hey, I like working on new concepts and follow an approach of keeping things as simple as possible. Appreciates neat architecture and intelligent design.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade