Ruby Quiz (Easy) #7

question mark

Question

What would be the output of this code snippet?

[gist https://gist.github.com/cawel/69131717ccbe95700e67]

 

Solution

The output would be [1, 2, 3]. The entire array is not modified by the Array#each method. This is because the iterator, while traversing the collection, passes a copy of each element in turn, to the block.

If you want to dig a bit, if you look in the C code from Ruby 1.8.4 in the array.c file, the parameter yielded to the block is passed by value, as opposed to being passed by address (which would then allow modification of its value).

[gist https://gist.github.com/cawel/17565cd0125a1eddeab9]
Advertisements

Got a comment?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: