Ruby/Array/Array Index

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

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

Содержание

Assign string value to an integer array

x = [1, 2, 3, 4]
 
x[2] = "Fish" * 3
puts x[2]



Elements can be accessed by their index (their position within the array).

x = [1, 2, 3, 4]
puts x[2]



get the flip side with index.

# It returns the index of the first element that matches the object:
q1 = %w[ January February March ]
q1.index "March" # => 2



Mix up an array

array = [1,2,3,4,5]
new_array = []
front_index = 0
back_index = array.length-1
while front_index <= back_index
  new_array << array[front_index]
  front_index += 1
  if front_index <= back_index
   new_array << array[back_index]
    back_index -= 1
  end
end
p new_array                                 # => [1, 5, 2, 4, 3]



The first element in the array corresponds to array index 0, not 1,

# and the second element is at index 1, the third at index 2, and so on.
array = [1, 2, 3]
array[0] = 4      #assigns 4 to array[0]
array[1] = 5      #assigns 5 to array[1]
array[2] = 6      #assigns 6 to array[2]
puts array[2]     #prints 6



The last element in the array is -1, the previous one -2, the previous one -3

array = ["Hello", "there", "AAA", 1, 2, 3]
puts array[-1]            #prints 3
puts array[-2]            #prints 2
puts array[-3]            #prints 1



To change an element, you can simply assign it a new value or manipulate it

x = [1, 2, 3, 4]
x[2] += 1
puts x[2]



Use a variable (or a constant) as an array index

array = ["Hello", "there", "AAA", 1, 2, 3]
index_value = 0
puts array[index_value]   #prints "Hello"
index_value = 1
puts array[index_value]   #prints "there"
index_value = 2
puts array[index_value]   #prints "AAA"



Use negative array indices in Ruby.

# Negative indices count from the end of the array back to the beginning of the array. 
array = ["Hello", "there", "AAA", 1, 2, 3]
puts array[-1]            #prints 3



Use until and array element to loop through an array

array = ["cherry", "strawberry", "orange"]
index = 0
until index == array.length
  puts "At position #{index}: #{array[index]}"
  index += 1
end



Use while and array index to get element from an array

array = ["cherry", "strawberry", "orange"]
index = 0
while index < array.length
  puts "At position #{index}: #{array[index]}"
  index += 1
end