ruby访问器_Ruby中的迭代器

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)

Times Iterator example in Ruby

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关键字之前给定的timestimes关键字知道从1开始并停止于times关键字之前指定的数字。

Here, 5 is given. So, it prints "Hello, World" for 5 times.

Ruby:最多迭代器 (Ruby: Upto Iterator)

Upto Iterator example in Ruby

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 :

上面代码的输出是:

Upto Iterator example in Ruby

Likewise, we can sum the value of first ten numbers by,

同样,我们可以将前十个数字的值相加,

Upto Iterator example in Ruby

Ruby:步骤迭代器 (Ruby: Step Iterator)

Step Iterator example in Ruby

It's somewhat similar to upto iterator.

它有点类似于upto迭代器。

Step Iterator example in Ruby

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 :

上面程序的输出是:

Step Iterator example in Ruby

To print the sum of odd numbers up to 10

打印最多10个奇数和

Step Iterator example in Ruby

The output of the above program is :

上面程序的输出是:

Step Iterator example in Ruby

Remember, Iterators provide more flexibility when compared to a while and do while loop in traditional programming languages.

请记住,与传统编程语言中的whiledo while循环相比, 迭代器提供了更大的灵活性。

翻译自: https://www.studytonight.com/ruby/iterator-in-ruby

ruby访问器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值