Pierre Barbier de Reuille
3/28/2006 12:54:00 PM
Victor Shepelev a écrit :
> Maybe dumb question, but...
>
> I have not found anything like Array.resize, i.e.
>
> a = [1,2]
>
> a.resize(5) #=> [1,2,nil,nil,nil] a.resize(5, 3) #=> [1,2,3,3,3]
>
>
> I can use Array.fill, but
>
> a.fill(3, a.size, a.size+2)
>
> looks a bit ugly, not?
>
> Moreover, if I want to resize to size lesser then array is, I need
> slice.
>
> Why not to have all-purpose resize?
>
> Victor.
>
You may try :
a = [1,2]
a.fill(3, -1, 3) #=> [1,2,3,3,3]
So you may code yourself your resize :
class Array
def resize(new_size, value=nil)
if new_size < length
slice!(new_size, length)
else
fill(value, -1, new_size-length)
end
self
end
end
Pierre