Last active
December 19, 2015 04:19
-
-
Save scarow/5896176 to your computer and use it in GitHub Desktop.
Exercise: Create a method to pad an array Implement Array#pad and Array#pad!. Each method accepts a minimum size (non-negative integer) and an optional pad value as arguments. If the array's length is less than the minimum size, Array#pad should return a new array padded with the pad value up to the minimum size. For example, ruby [1,2,3].pad(5)…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def pad!(min_size, value = nil) | |
length = self.length | |
size = min_size - length | |
if min_size <= length | |
return self | |
end | |
if min_size > length | |
size.times do | |
self << value | |
end | |
return self | |
end | |
end | |
def pad(min_size, value = nil) | |
length = self.length | |
size = min_size - length | |
self_dup = self.dup | |
if min_size <= length | |
return self_dup | |
end | |
if min_size > length | |
size.times do | |
self_dup << value | |
end | |
return self_dup | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment