有没有一种简单的方法可以在Ruby中生成有序对 [英] Is there an easy way to generate ordered couples in Ruby

查看:63
本文介绍了有没有一种简单的方法可以在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中生成有序对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆