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_linemethod on array takes element @ beginning of array , puts @ end. hint: remember,array#shiftremoves first element, ,array#pushadds 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:
- define class of method (array).
- define method (next in line)
- the third line removes first element of array
- 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
Post a Comment