ruby访问器
Iterators
allow us to traverse a range and to do something certain number of times within a range. It's easier to demonstrate Iterator
rather than describing it.
Iterators
我们可以遍历范围并在范围内执行一定次数的操作。 演示Iterator
比描述Iterator
容易。
Ruby:Times迭代器 (Ruby: Times Iterator)
This code executes the statements inside the do block for the number of times given before times
keyword. times
keyword knows to start from 1 and stop at which the number specified before times
keyword.
这段代码执行do块内的语句的次数为times
关键字之前给定的times
。 times
关键字知道从1开始并停止于times
关键字之前指定的数字。
Here, 5 is given. So, it prints "Hello, World" for 5 times.
Ruby:最多迭代器 (Ruby: Upto Iterator)
It iterates through the range starting from the number specified before the upto
keyword and up to the number specified in the upto
keyword. In our case, starting from 1 up to 10. For each iteration, it stores the value to the variable x. Using the value in the variable x, we can perform our desired operations by specifying it in the do block.
它通过迭代从之前指定的数字开始的范围upto
关键字和至多在指定数量upto
关键字。 在我们的情况下,从1到10。对于每次迭代,它将值存储到变量x 。 使用变量x中的值,我们可以通过在do块中指定它来执行所需的操作。
The output of the above code is :
上面代码的输出是:
Likewise, we can sum the value of first ten numbers by,
同样,我们可以将前十个数字的值相加,
Ruby:步骤迭代器 (Ruby: Step Iterator)
It's somewhat similar to upto
iterator.
它有点类似于upto
迭代器。
It iterates between the range specified by the user. For each iteration it increases the value of the variable x
specified by the step counter.
在用户指定的范围之间进行迭代。 对于每次迭代,它都会增加由步数计数器指定的变量x
的值。
The output of the above program is :
上面程序的输出是:
To print the sum of odd numbers up to 10
打印最多10个奇数和
The output of the above program is :
上面程序的输出是:
Remember, Iterators provide more flexibility when compared to a while
and do while
loop in traditional programming languages.
请记住,与传统编程语言中的while
和do while
循环相比, 迭代器提供了更大的灵活性。
ruby访问器