Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .insert work?

Tags:

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) mysterious 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?
like image 980
Bodhidarma Avatar asked Jun 24 '11 02:06

Bodhidarma


People also ask

How do I know if my Insert key is working?

Go to file > word options > advanced > editing options. Check the box that says, “use the Insert key to control overtype mode” Now the insert key works.

What does home key do?

The Home key helps in navigation of applications or a word processing programs. It is most commonly used to make the cursor move to the beginning of the line in a text editing program. The Home key has the opposite functionality of the End key.

How do I use the INS button on my HP laptop?

Therefore, when Num Lock is on, pressing Shift + Numpad-0 will function as an Insert Key.


2 Answers

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.

like image 52
the Tin Man Avatar answered Sep 29 '22 16:09

the Tin Man


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.

like image 31
Jake Petroules Avatar answered Sep 29 '22 15:09

Jake Petroules