Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for padding an array in Ruby

Here's what I have now and it is somewhat working:

def padding(a, b, c=nil)
  until a[b-1]
    a << c
  end
end

This is when it works:

a=[1,2,3]
padding(a,10,"YES")
=>[1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]

a[1,2,3]
padding(a,10,1)
=>[1, 2, 3, 1, 1, 1, 1, 1, 1, 1]

But it crashes when I do not enter a value for "c"

a=[1,2,3]
padding(a,10)
Killed

How should I append this to avoid a crash? Additionally, how would you suggest changing this method to use it as follows:

[1,2,3].padding(10)
=>[1,2,3,nil,nil,nil,nil,nil,nil,nil]
[1,2,3].padding(10, "YES")
=>[1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]

I've seen other padding methods on SO, but they don't seem to be working as intended by the authors. So, I decided to give making my own a shot.

like image 952
marinatedpork Avatar asked Aug 05 '14 17:08

marinatedpork


1 Answers

Do you know Array#fill method :-

It does, what you exactly looking for. If it exist, why you want your own.

arup@linux-wzza:~> pry
[1] pry(main)> a=[1,2,3]
=> [1, 2, 3]
[2] pry(main)> a.fill('YES', 3...10)
=> [1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]
[3] pry(main)>

You can fill your array, whatever way you want. It is a cool implementation. Give it a try.

Read it in your console :

arup@linux-wzza:~> ri Array#fill

= Array#fill

(from ruby site)
------------------------------------------------------------------------------
  ary.fill(obj)                                 -> ary
  ary.fill(obj, start [, length])               -> ary
  ary.fill(obj, range )                         -> ary
  ary.fill { |index| block }                    -> ary
  ary.fill(start [, length] ) { |index| block } -> ary
  ary.fill(range) { |index| block }             -> ary

------------------------------------------------------------------------------

The first three forms set the selected elements of self (which may be the
entire array) to obj.

A start of nil is equivalent to zero.

A length of nil is equivalent to the length of the array.

The last three forms fill the array with the value of the given block, which
is passed the absolute index of each element to be filled.

Negative values of start count from the end of the array, where -1 is the last
element.

  a = [ "a", "b", "c", "d" ]
  a.fill("x")              #=> ["x", "x", "x", "x"]
  a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
  a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
  a.fill { |i| i*i }       #=> [0, 1, 4, 9]
  a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
like image 163
Arup Rakshit Avatar answered Sep 27 '22 17:09

Arup Rakshit