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
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.
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.
Therefore, when Num Lock is on, pressing Shift + Numpad-0 will function as an Insert Key.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With