# Re: Showing part of an array

**URL:** <https://www.ruby-forum.com/t/re-showing-part-of-an-array/99432>\
**Category:** Ruby\
**Created:** [July 22, 2006, 6:23pm UTC](https://www.ruby-forum.com/t/re-showing-part-of-an-array/99432 "2006-07-22T18:23:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [July 22, 2006, 6:23pm UTC](https://www.ruby-forum.com/t/re-showing-part-of-an-array/99432/1 "2006-07-22T18:23:59Z")

</div>

Rosina,

I’ll explain this line:

colors[0…2].collect{ |color| color.name }.join(’, ')

for an Array colors , say colors=[‘red’,‘green’,‘yellow’],

you can choose the first three entries by  
colors[0…2],  
then you map the elements of this Array (i.e., the Strings using the  
collect command.  
To be able to deal with them, you give the iterator a name, say  
|color|.  
But that’s for the individual entries - you’re trying to puit together a  
String  
consisting of all the elements of color[0…2] …

color.name only makes sense if you had defined it as a function.  
Then you can map the entire Array to another Array and show  
only the first so-and-so many of them. The following code translates  
some color names into French. (I am not using the most compact  
syntax Ruby is capable of below, since I want to keep things  
easily understandable):

class String  
def name  
if self==‘red’  
return ‘rouge’  
end

if self==‘blue’  
return ‘bleu’  
end  
if self==‘green’  
return ‘vert’  
end  
if self==‘white’  
return ‘blanc’  
end  
if self==‘yellow’  
return ‘jaune’  
end  
return ‘unknown color’ # Computer doesn’t know so much French  
end  
end

Best regards,

Axel

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [July 22, 2006, 6:39pm UTC](https://www.ruby-forum.com/t/re-showing-part-of-an-array/99432/2 "2006-07-22T18:39:13Z")

</div>

unknown wrote:

> Rosina,
> 
> I’ll explain this line:
> 
> colors[0…2].collect{ |color| color.name }.join(’, ')

Thank you for the explanation! That helped me understand what’s going on  
in the collect better. Yes, name is defined. This is actually from a  
rails app and colors is the table which has a name attribute (among  
others), so this line works great if I want to show all the colors. In  
another post a few minutes ago, I explained how I am actually using this  
in a call to another function from in ajax\_scaffold. I was trying to  
simplify it somewhat to get at the core of the problem, but I think in  
my lack of understanding, I simplified too much

Cheers,  
Rosina
