ruby - Is it possible to alter an Array object's length? -
how 1 alter self in array totally new array? how fill in commented portion below?
class array def change_self #make array `[5,5,5]` end end i understand this: why can't change value of self? , know can't assign self new object. when do:
arr = [1,2,3,4,5] arr contains reference array object. can add method array class alters array, like:
self[0] = 100 but possible change length of array referenced arr? how these values stored in array object?
you asking 3 different questions in title , in text:
is possible alter
arrayobject's length usingarraymethod?
yes, there 20 methods can (potentially) change length of array:
<<increases length 1[]=can alter length arbitrarily, depending on argumentsclearsets length 0compact!can decrease length, depending on contentsconcatcan increase length, depending on argumentsdeletecan decrease length, depending on arguments , contentsdelete_atcan decrease length, depending on argumentsdelete_if/reject!can decrease length, depending on arguments , contentsfillcan increase length, depending on argumentsinsertincreases lengthkeep_if/select!can decrease length, depending on arguments , contentspopdecreases lengthpushincreases lengthreplacecan alter length arbitrarily, depending on arguments , contents (it replacesarraydifferentarray)shiftdecreases lengthslice!decreases lengthuniq!can decrease length, depending on contentsunshiftincreases length
when monkey patching array class, how 1 alter "self" totally new array? how fill in commented portion below?
class array def change_self #make array [5,5,5] no matter end end
class array def change_self replace([5, 5, 5]) end end how these values stored in
arrayobject?
we don't know. ruby language specification not prescribe particular storage mechanism or implementation strategy. implementors free implement arrays way like, long obey contracts of array methods.
as example, here's array implementation in rubinius, find readable (at least more yarv):
vm/builtin/array.cpp: core methods , data structureskernel/bootstrap/array.rb: minimal implementation bootstrapping rubinius kernelkernel/common/array.rb: bulk of implementation
for comparison, here topaz's implementation:
and jruby:
Comments
Post a Comment