有没有一种简单的方法可以在Ruby中生成有序对

编程入门 行业动态 更新时间:2024-10-20 11:57:50
本文介绍了有没有一种简单的方法可以在Ruby中生成有序对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是否有与 Range 相似的东西,但不是整数,而是有序夫妇(x,y)。我想知道是否有一种简单的方法可以执行以下操作:

I was wondering if there is something similar to the Range but not with integers but with ordered couples (x, y). I am wondering if there is an easy way to do something like this:

((1,2)..(5,6)).each {|tmp| puts tmp} #=> (1,2) (3,4) (5,6)

编辑:也许我不是100%清楚我的问题:)我会尝试用另一种方式问它。

EDIT: Maybe I was not 100% clear in my question :) I'll try to ask it in a different way.

如果我有这些夫妻:(3,4)和(5,6),我正在寻找一种方法来帮助我生成:

If I had these couples: (3,4) and (5,6) I am looking for a way to help me generate:

(3,4), (4,5), (5,6)

如果我有更好地说明一下:如果夫妻是(x,y)->

if I had to exlpain it better : if the couples are (x,y)->

(x0,y0), ((x0+1),(y0+1)), ((x0+2), (y0+2)) and so on .

推荐答案

您可以将数组用作Range元素,例如:

You can use arrays as Range elements, such as:

> t = [1, 2]..[3, 4] => [1, 2]..[3, 4]

但是,它不能被迭代,因为 Array 类缺少 succ 方法。

However, it cannot be iterated, because the Array class lacks a succ method.

> t.each {|tmp| puts tmp} TypeError: can't iterate from Array from (irb):5:in `each' from (irb):5 from D:/Programmes/Ruby/bin/irb:12:in `<main>'

所以如果你想允许使用数组进行迭代,定义一个执行所需操作的 Array#succ 方法:

So if you want to allow iterating using arrays, define an Array#succ method that does what you want:

class Array def succ self.map {|elem| elem + 1 } end end

这将为您提供:

> t = [1, 2]..[3, 4] => [1, 2]..[3, 4] > t.each {|tmp| p tmp} [1, 2] [2, 3] [3, 4] => [1, 2]..[3, 4]

更多推荐

有没有一种简单的方法可以在Ruby中生成有序对

本文发布于:2023-05-28 06:55:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!