Re: Showing part of an array

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

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