Re: Showing part of an array

You can use this function:

class Array
def show_part
if self.length>2
p self[0…2].join(’, ‘)+’, …’
else
p self.join(’, ')
end
end
end

… anbd apply it like this :

colors = [“black”,“white”,“red”,“yellow”,“green”]
colors.show_part
two_colors = [“black”,“white”]
two_colors.show_part
three_colors = [“black”,“white”,‘red’]
three_colors.show_part

Best regards,

Axel

Thanks, Axel

How about if you’re using it on an array consisting of both an id and a
name so that

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

Cheers,
Rosina

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs