Project

General

Profile

Actions

Feature #21284

open

Request: add `Array#pad` method

Added by MatzFan (Brian Cohen) 2 days ago. Updated 1 day ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:121727]

Description

A method to pad an array of arbitrary length with objects up to a specified array size does not currently exist.

Array#fill does not do this and I therefore propose the following method:

class Array
  def pad(pad_to_length, object = nil)
    fill(object, size, pad_to_length - size)
  end
end

I have provided an answer to a Stack Overflow question asking how this can be done in Ruby. I've also explained in a comment on the answer which suggests using Array#fill why this does not meet the exact need.

Updated by nobu (Nobuyoshi Nakada) 2 days ago

It may be possible with Array#fill and start-exclusive range?

ary.fill(object, -1^..padding_length)

Updated by MatzFan (Brian Cohen) 1 day ago

When I try and run that code, e.g.

[1, 2, 3].fill(nil, -1^..10)
'Integer#^': Range can't be coerced into Integer (TypeError)

In any case pad(10) is much prettier IMHO.

Actions

Also available in: Atom PDF

Like0
Like0Like0