开发者

How does .insert work?

I'm trying to figure out what the insert function does in Ruby.

I've consulted Google and ruby-doc.com but the explanation is not sufficient to describe this (seemingly) m开发者_运维知识库ysterious function.

Here's what's confusing me:

a = %w{a b c d}
puts a.insert(4, 5)  output = a,b,c,d,5

The first question raised is, why is the 4 not inserted?

puts a.insert(2,2,6)

The output is:

a
b
2
6
c
d

Two questions raised by this are

  1. Why is 2 not inserted twice?
  2. Why are 2 and six (seemingly) arbitrarily placed between b and c?


I'm not sure what the confusion is. From the Ruby docs:

ary.insert(index, obj...)  -> ary

Inserts the given values before the element with the given index (which may be negative).

a = %w{ a b c d }
a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]

So, a.insert(2, 99) is inserting 99 into the array just before array offset 2. Remember that an array's index starts at 0, so that is the third slot in the array.

The second example is inserting the array [1,2,3] into the second-from-the-last array slot, because negative offsets count from the end of the array. -1 is the last index, -2 is the second to last.

The Array docs say it well:

Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array---that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

These are VERY important concepts to learn in programming in general, not just in Ruby.


Looks like the first parameter is the index to insert at, and the rest are the items to insert.

The docs would appear to confirm this, listing the function as ary.insert(index, obj...) → ary

If you simply want to add some values to the end of the array (I don't know Ruby syntax but this should be correct) I think you will want to call a.insert(a.length, 4, 5) or a.insert(a.length, 2, 2, 6), for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜