Ruby/Array/Array Each

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

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

each method goes through each element of the array and passes it as a parameter to the code block you supply.

[1, "test", 2, 3, 4].each { |element| puts element.to_s + "X" }



Identify the Array and Hash of Customers

customer_array = ["A","B","C","D","E","F"]
customer_hash = {
"A" => "Fiction",
"B" => "Mystery",
"C" => "Computer",
"D" => "Fiction",
"E" => "Sports",
"F" => "Fiction"
}
j=0
for i in 0...customer_array.length
     if customer_hash[customer_array[i]]=="Fiction"
            puts "#{customer_array[i]} has brought fiction books"
            customer_array[j]=customer_array[i]
            j=j+1
     end
end



If you have a collection, such as an array or a range, you can also use the Ruby each iterator to create a loop.

grades = [88, 99, 73, 56, 87, 64]
sum = 0
grades.each do |grade|
  sum += grade
end
average = sum / grades.length
puts average