0
Explain the code in ruby
What is the output of this code ? items = ['place","key","holder"] items[1,0] = ["bottle","my"] puts items[-3] , items[-2], items[-1]
2 Answers
+ 1
It's easier to understand if you explore and run the code.
items = ["place", "key", "holder"]
items[1,0] = ["bottle", "my"]
print items
#Output: ["place", "bottle", "my", "key", "holder"]
From above, it seems that new elements is being inserted into the array.
Referring to documentation, ary[start, length] = obj or other_ary
Elements are inserted into the array at start if length is zero.
Hence, items[1,0] = ["bottle", "my"] means "bottle" and "my" is inserted into the array at index 1 onward.
items[-1] referring to the last element.
Hence, items[-3] , items[-2], items[-1] referring to the last three elements "my", "key", "holder".
Hope the above clarifies. Thanks for asking as I had also learn new ways of adding elements into array. =)
0
items = ["place","key","holder"]
Creates a zero based list where "place" is in the zero position.
items[1,0] = ["bottle","my"]
Slices the new list with "bottle" and "my" into the items list at the 1 position ("key") and extends from that position 0 places so none of the current list items are overwritten.
Now the items list is:
["place", "bottle", "my", "key", "holder"]
puts prints to the console.
items[-3] works from the end of the last back 3 to get
"my"
items[-2] gets "key"
items[-1] gets "holder"
so the output is:
my
key
holder