Can someone explain how map! / connect! works in this case?

I just don’t get it, how does it know which value to write out? If I
change the array number say to 10 instead of three and change the word
“three” to “ten” in the block it comes as nil… is there something
special about 1…3 that I am missing?

ary = [0,1,1,1,1,3]
ary.map! { |num| %w(zero one two three)[num] }

p ary
[“zero”, “one”, “one”, “one”, “one”, “three”]

On Fri, May 18, 2012 at 9:27 AM, Christopher D.
[email protected]wrote:

• Aziz M. Bookwala

|
Github http://github.com/azizmb

When you use ary = [0,1,1,1,1,10] map! ends up trying to do this:

%w(zero one two ten)[10]

So it’s trying to get the tenth element of an array of only 4 elements,
that’s why it returns nil, the only way to make it work as you want is:

%w(zero one two three four five six seven eight nine ten)[10] # => “ten”

So an array of 11 elements.

On 18 May 2012 04:57, Christopher D. [email protected] wrote:

ary = [0,1,1,1,1,3]
ary.map! { |num| %w(zero one two three)[num] }

I just don’t get it, how does it know which value to write out?

you’re taking the numbers 0,1,1,1,1,3 and for each of them you’re
populating an array with the values from another array at the index
that corresponds to the number you’re operating on at the time.
It doesn’t “know” which number to write out, you’re telling it to go
get whatever element is at the index.

If I
change the array number say to 10 instead of three and change the word
“three” to “ten” in the block it comes as nil…

If you change one of them to “10”, then the map is not going to find
an element in your “%w(zero one two three)” array at index 10, so it
returns nil.

is there something
special about 1…3 that I am missing?

No, but it would probably be best to familiarise yourself with the
Enumerable methods’ documentation. Or maybe go through the Ruby koans
to experiment.

BTW What on earth are you trying to achieve with this code?