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 array object's length using array method?

yes, there 20 methods can (potentially) change length of array:

  • << increases length 1
  • []= can alter length arbitrarily, depending on arguments
  • clear sets length 0
  • compact! can decrease length, depending on contents
  • concat can increase length, depending on arguments
  • delete can decrease length, depending on arguments , contents
  • delete_at can decrease length, depending on arguments
  • delete_if / reject! can decrease length, depending on arguments , contents
  • fill can increase length, depending on arguments
  • insert increases length
  • keep_if / select! can decrease length, depending on arguments , contents
  • pop decreases length
  • push increases length
  • replace can alter length arbitrarily, depending on arguments , contents (it replaces array different array)
  • shift decreases length
  • slice! decreases length
  • uniq! can decrease length, depending on contents
  • unshift increases 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 array object?

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):

for comparison, here topaz's implementation:

and jruby:


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -