Folding an array by an offset in Ruby.
by Rabbit
This method is difficult to explain, so here’s an example.
Update! I described this method to my girlfriend, and she ever so brilliantly came up with the analogy of folding pages in a magazine. So I changed the name of the method from #shift_by to #fold_at. Thanks, babe!
>> Date::DAYNAMES => ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] >> Date::DAYNAMES.fold_at(1) => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
Get it? Drop count number of elements from the beginning of your array and append them to the back. Thus, “folding over” your array.
class Array def fold_at(count) duplicate = self.dup fold = duplicate.slice!(0...count) duplicate + fold end def fold_at!(count) self.replace(fold_at(count)) end end