Ruby/Statement/upto
Материал из Wiki.crossplatform.ru
(Различия между версиями)
Версия 17:10, 26 мая 2010
do all the times tables from 1 to 12
1.upto(12) { |i| 1.upto(12) { |j| print i.to_s + " x " + j.to_s + " = ", j * i, "\n"} }
Example of upto that prints out a times table for 2
1.upto(12) { |i| print "2 x " + i.to_s + " = ", i * 2, "\n"}
Interpolation with upto and array
array = ["junk", "junk", "junk", "val1", "val2"] 3.upto(array.length-1) { |i| puts "Value #{array[i]}" } # Value val1 # Value val2
One date may upto another
require "date" the_first = Date.new(2004, 1, 1) the_fifth = Date.new(2004, 1, 5) the_first.upto(the_fifth) { |x| puts x }
The upto Method and for loop
# The upto method is a convenience method that does the same thing as a for loop # The Integer, String, and Date classes all have upto methods for i in 1..10 print i, " " end # => 1 2 3 4 5 6 7 8 9 10 # Compare this with upto, which does exactly the same thing: 1.upto(10) { |i| print i, " " } # => 1 2 3 4 5 6 7 8 9 10
upto with / without {}
1.upto 3 do |x| puts x end # 1 # 2 # 3 1.upto(3) { |x| puts x } # 1 # 2 # 3
Use an upto Iterator to reference array element
fruits = ["peaches", "pumpkins", "apples", "oranges"] print "We offer " 0.upto(fruits.length - 1) do |loop_index| print fruits[loop_index] + " " end
use curly braces ({}):
fruits = ["peaches", "pumpkins", "apples", "oranges"] 0.upto(fruits.length - 1) { |loop_index| print fruits[loop_index] + " " }
uses the upto iterator to create a loop similar to a for loop from other languages
fruits = ["peaches", "pumpkins", "apples", "oranges"] 0.upto(fruits.length - 1) do |loop_index| print fruits[loop_index] + " " end
use the upto iterator, which is what traditional for loops translate into in Ruby.
grades = [88, 99, 73, 56, 87, 64] sum = 0 0.upto(grades.length - 1) do |loop_index| sum += grades[loop_index] end average = sum / grades.length puts average