I could not understand why, in Ruby, Array#slice and Array#slice! behave differently than Array#sort and Array#sort! (as one returns the results in a new array, and the other works on the current object).
With sort first (without a break) returns a sorted copy of the current array, and sort! sorts the current array.
slice returns an array with the specified range, and slice! removes the specified range from the current object.
What is the reason Array#slice! behaves like this, instead of making the current Array object with the specified range?
Example:
a = [0,1,2,3,4,5,6,7,8,9] b = a.slice( 2,2 ) puts "slice:" puts " a = " + a.inspect puts " b = " + b.inspect b = a.slice!(2,2) puts "slice!:" puts " a = " + a.inspect puts " b = " + b.inspect
Output:
slice: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = [2, 3] slice!: a = [0, 1, 4, 5, 6, 7, 8, 9] b = [2, 3]
http://ideone.com/77xFva
ruby behavior design-decisions
Vargas
source share