Creating a Ruby method that pads an Array -


i'm working on creating method pads array, , accepts 1. desired value , 2. optional string/integer value. desired_size reflects desired number of elements in array. if string/integer passed in second value, value used pad array elements. understand there 'fill' method can shortcut - cheating homework i'm doing.

the issue: no matter do, original array returned. started here:

class array   def pad(desired_size, value = nil)      desired_size >= self.length ? return self : (desired_size - self.length).times.do { |x| self << value }    end end  test_array = [1, 2, 3] test_array.pad(5) 

from researched issue seemed around trying alter self's array, learned .inject , gave whirl:

class array   def pad(desired_size, value = nil)      if desired_size >= self.length       return self      else        (desired_size - self.length).times.inject { |array, x| array << value }     return array     end   end end test_array = [1, 2, 3] test_array.pad(5) 

the interwebs tell me problem might reference self wiped out altogether:

class array   def pad(desired_size, value = nil)     array = []     self.each { |x| array << x }     if desired_size >= array.length       return array      else        (desired_size - array.length).times.inject { |array, x| array << value }     return array     end   end end test_array = [1, 2, 3] test_array.pad(5) 

i'm new classes , still trying learn them. maybe i'm not testing them right way test_array? otherwise, think issue method recognize desired_size value that's being passed in. don't know go next. advice appreciated.

thanks in advance time.

in 3 of tries, returning original array if desired_size greater original array size. have backwards. in other words, return instead of padding.

your first attempt close. need to: 1) fix conditional check. 2) it's ok modify self array, more complicated tries not necessary. 3) make sure return self no matter do.

by modifying self, not return modified array, change array held variable test_array. if do:

test_array = [1, 2, 3] puts test_array.pad(5, 4).inspect  // prints [1, 2, 3, 4, 4] puts test_array                    // prints [1, 2, 3, 4, 4] 

in ruby, when function modifies self, function name ends !, if write modifying self, better name pad!.

if want write doesn't modify self, start with:

array = self.dup 

and of operations on array.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -