From: "Guy N. Hurst" Date: 2001-05-02T01:36:17+09:00 Subject: [ruby-talk:14502] Re: RCR: Array#insert Yukihiro Matsumoto wrote: > > Hi, > > In message "[ruby-talk:14486] Re: RCR: Array#insert" > on 01/05/01, "Guy N. Hurst" writes: > > |What about his alternate version that handled negative indices > |differently? [ruby-talk:14371] further down. > > Hmm, there's tradeoff between inconsistency (to []= at least) and > handiness. Let me ponder for a while. Discussions are welcome. We did discuss this before also, in the thread starting at [ruby-talk:5692], http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/5692, and Weirich's post [ruby-talk:5700] cleared it up, I think: >>> Don't think of it as "insert before" or "insert after". Think of it as "insert at". After the assertion, the inserted value will be *at* the given index. E.g. After ... a.insert (index, value) then ... a[index] == value whether index is positive or negative. <<< Currently, I consider the current approach as inconsistent. Here's one aspect of it: a=[1,2,3] a[0,0] = "a" # ["a",1,2,3] a[1,0] = "b" # ["a","b",1,2,3] a[-1,0] = "c" # ["a","b",1,2,"c",3] One might think that they are inserting "at" a particular location, but when using negative indices, realize it was always inserting "before". but b=[1,2,3,4] b[0] = "a" # ["a",2,3,4] b[1] = "b" # ["a","b",3,4,] b[-1] = "c" # ["a","b",3,"c"] Here, we are replacing "at" the given index. Aleksi brought it up again in [ruby-talk:5830], http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/5830. Dave saw no reason to change []= (citing availability of #push), nor for even adding #insert. (And you reminded me that there is #concat, and I also remember <<) My point is that if we have #insert, why not make it able to insert at *any* place in the array? But then, I also think []= should act the same way, which perhaps would break older scripts relying on [-1,0]= to insert at [-2] ? But consider that people have already implemented #insert in Ruby. By making it part of Ruby, it will become "standard", so I propose that it should handle negative indices properly, regardless of how [pos,0]= works. 1) because it will help the transition of fixing [pos,0]= as people start to prefer using #insert over [pos,0]= 2) because it will eliminate the need for us to override a 'wrong' #insert with our own version of #insert ;-) 3) would support using single function for inserting anywhere, reducing code About reducing code.... Why should I always do this in Ruby: a=[1,2,3] val="value" print "enter position to insert value:" pos = gets.to_i if pos == -1 a.push(val) elsif pos < -1 a.insert(pos+1,val) else a.insert(pos, val) end When I can do this: a=[1,2,3] val="value" print "enter position to insert value:" pos = gets.to_i a.insert(pos,val) ???? Thank you for your time. Guy N. Hurst -- HurstLinks Web Development http://www.hurstlinks.com/ Norfolk, VA 23510 (757)623-9688 FAX 623-0433 PHP/MySQL - Ruby/Perl - HTML/Javascript