Ruby/Array/Two Array Indices

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

array[1, 2] references two array elements, starting with the element at index 1, and this statement replaces two elements in the array, not just one:

array = ["Hello", "there", "AAA", 1, 2, 3]
array[1, 2] = "here"
p array



Assigning a value to array[3, 0] did not replace any element in the array; it inserted a new element starting at index 3 instead.

array = ["Hello", "there", "AAA", 1, 2, 3]
array[3, 0] = "pie"
puts array



In Ruby the first index is the start location and the second holds the count: array[start, count].

array = ["Hello", "there", "AAA", 1, 2, 3]
array[1] = "here"
p array
array = ["Hello", "there", "AAA", 1, 2, 3]
array[1, 1] = "here"
p array



Instead of [], you can also use the slice method, another alias

year = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
year.slice(1) # => 2001
year.slice(0,4) # => [2000, 2001, 2002, 2003]
year.slice(0..2) # => [2000, 2001, 2002]
year.slice(0...2) # => [2000, 2001]



specify where to start in the array and how many elements you want

year = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
year[0, 3] # => [2000, 2001, 2002]
# The 0 is the start parameter. It says to start at 0, or the beginning of the array. 
# The second is the length parameter, which tells how many elements you want.



use a range:

year = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
year[7..9] # => [2007, 2008, 2009]
#two dots means "include both elements," and three dots means "don"t include the last element."



Using Two Array Indices

array = ["Hello", "there", "AAA", 1, 2, 3]
array[2, 1] = "pal"
p array
array = ["Hello", "there", "AAA", 1, 2, 3]
array[3, 0] = "pie"
p array
array = ["Now", "is", 1, 2, 3]
array[2, 0] = ["the", "time"]
p array
array = ["Hello", "there", "AAA", 1, 2, 3]
array2 = array[3, 3]
p array2