关于红宝石范围?
像这样
range = (0..10)
我怎样才能得到这样的数字:
0 5 10
每次加五但小于10
如果范围=(0..20)那么我应该得到这个:
0 5 10 15 20
like this
range = (0..10)
how can I get number like this:
0 5 10
plus five every time but less than 10
if range = (0..20) then i should get this:
0 5 10 15 20
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
.step()
进行通过给定的步骤。给出...
正如 dominikh 所提到的,您可以在末尾添加
.to_a
以获得数字列表的可存储形式:(0..20).step(5)。 to_a
Try using
.step()
to go through at a given step.gives...
As mentioned by dominikh, you can add
.to_a
on the end to get a storable form of the list of numbers:(0..20).step(5).to_a
就像戴夫说的,但添加到_a:
Like Dav said, but add to_a:
http://ruby-doc 中描述的
step
方法。 org/core/classes/Range.html 应该可以完成这项工作,但严重损害可能会损害可读性。考虑一下:
您可能会认为步骤(5)会产生一个新的范围,就像 Why_ 的问题最初的意图一样。但是,如果您想“重用”0-5-10-15-20 范围,则每个都会在 (0..20) 上调用,并且必须由另一个步骤(5) 替换。
也许您会可以使用类似
(0..3).map{|i| 的东西我*5}
?但是“坚持”步骤方法的结果
.to_a
也应该可以正常工作 。The
step
method described in http://ruby-doc.org/core/classes/Range.html should do the job butseriously harmsmay harm the readability.Just consider:
You may think that step(5) kind of produces a new Range, like why_'s question initially intended. But the each is called on the (0..20) and has to be replaced by another step(5) if you want to "reuse" the 0-5-10-15-20 range.
Maybe you will be fine with something like
(0..3).map{|i| i*5}
?But "persisting" the step method's results with
.to_a
should also work fine.