Ruby/Array/Array Elements

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

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

Содержание

Accessing Elements

q1 = %w[ January February March ]
#you can access the first element of the array, element 0, with the 0 index:
q1[0] # => January
# Access the last element of the array, element 2, with:
q1[2] # => March



Access the last element in the array

q1 = %w[ January February March ]
q1[-1] # => March



Change character case of an element

a = ["a","b","c"]
a[2].upcase!
a.fill(2..4) { "b" }
a[2].upcase!



have an array that contains objects from different classes, not all just one type.

# here"s an array that contains four elements, each a different kind of object
hodge_podge = ["January", 1, :year, [2006,01,01]]
# Use each to iterate over the array, and class to find what kind of object each element is:
hodge_podge.each {|e| print e.class, " " } # => String Fixnum Symbol Array



Replacing subarrays with []=

# To delete, assign an empty array
# To insert, assign to a zero-width slice
p a = ("a".."e").to_a    # => ["a","b","c","d","e"]
p a[0,2] = ["A","B"]     # a now holds ["A", "B", "c", "d", "e"]
p a[2...5]=["C","D","E"] # a now holds ["A", "B", "C", "D", "E"]
p a[0,0] = [1,2,3]       # Insert elements at the beginning of a
p a[0..2] = []           # Delete those elements
p a[-1,1] = ["Z"]        # Replace last element with another
p a[-1,1] = "Z"          # For single elements, the array is optional
p a[1,4] = nil           # Ruby 1.9: a now holds ["A",nil]
                         # Ruby 1.8: a now holds ["A"]: nil works like []



To change three of the elements to have German rather than English spelling.

# uses a range to change elements 5 through 7.
months = %w[ nil January February March April May June July August September October November December ]
months[5..7] = "Mai", "Juni", "Juli"



use the at method

q1 = %w[ January February March ]
q1.at(0) # => January



With -1, you access the last element in an array by looping back around with a negative number.

q1 = %w[ January February March ]
puts q1[1]
puts q1[-2]



With start and length parameters

months = %w[ nil January February March April May June July August September
October November December ]
months[5..7] = "Mai", "Juni", "Juli" 
 
months[5, 3] = "May", "June", "July"