ruby - Define a next_in_line method on Array that takes the element at the beginning of the array and puts it at the end -


here's instructions on i'm supposed do.

define next_in_line method on array takes element @ beginning of array , puts @ end. hint: remember, array#shift removes first element, , array#push adds element end.

i've tried dozen variations nothing seems work. here's thought work:

class array   define_method(:next_in_line)     new_array = self.shift()     new_array = new_array.push()   end end 

pardon non-programmer-speak syntax, here's thought doing:

  1. define class of method (array).
  2. define method (next in line)
  3. the third line removes first element of array
  4. the fourth line pushes removed element end.

then type: ["hi", "hello", "goodbye"].next_in_line()

here's error message when try it:

nomethoderror: undefined method 'push' "hi":string 

why doesn't code work?

the error because: when called without argument, self.shift returns element, not array.

to fix error, use this:

class array   def next_in_line     return self if empty?     push shift   end end  ["hi", "hello", "goodbye"].next_in_line # => ["hello", "goodbye", "hi"] 

note there's built-in array#rotate.


Comments