2013-12-16 25 views
2

我想知道是否有類似的範圍但不是整數,但與有序夫婦(x,y)。我想知道如果有一個簡單的方法做這樣的事情:有沒有一種簡單的方法來生成有序夫婦在紅寶石

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

編輯:也許我是在我的問題不是100%清楚:)我會試着問它以不同的方式。

如果我有這些夫婦:(3,4)和(5,6)我正在尋找一種方法來幫助我產生:

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

如果我有更好的exlpain它:如果夫婦爲(X,Y) - >

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

回答

2

您可以使用數組作爲範圍元素,如:

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

但是,它不能被重複,因爲Array類缺乏succ方法。

所以,如果你想使用迭代陣列允許,定義一個Array#succ方法你想要做什麼:

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] 
+0

謝謝你的回答。我知道猴子補丁不是一件好事,但是。說起來有沒有類似的方法來得到這個:[[5,4],[4,5],[3,6]]如果我有[5,4]和[3,6]?它與第一個邏輯不完全相同,但它具有相同的語義。我很好奇。 – user2128702

+0

爲什麼該方法的名稱必須是'succ'? – user2128702

+0

@ user2128702請參閱http://ruby-doc.org/core-2.0.0/Range.html#method-i-each「只有當範圍的開始對象支持succ方法時才能使用每種方法。」 。如果你想要自定義中介陣列,可能需要另一種方法 – SirDarius

1

您可以使用Enumerable#each_slice

1.9.3-p327 :001 > (1..6).each_slice(2).to_a 
=> [[1, 2], [3, 4], [5, 6]] 
+1

謝謝,但我沒有以正確的方式提出問題。現在有一個編輯。 – user2128702

+0

噢,我想SirDarius回答你的問題。 – rohit89

1

Ruby是一種對象 - 面向語言。所以,如果你想用一個「有序的對象」來做某件事,那麼你需要......好的...一個OrderedCouple對象。

class OrderedCouple < Struct.new(:x, :y) 
end 

OrderedCouple.new(3, 4) 
# => #<struct OrderedCouple x=3, y=4> 

嗯,看起來醜陋:

class OrderedCouple 
    def to_s; "(#{x}, #{y})" end 

    alias_method :inspect, :to_s 

    class << self; alias_method :[], :new end 
end 

OrderedCouple[3, 4] 
# => (3, 4) 

Range s的用於兩件事情:檢查包容和迭代。爲了將對象用作Range的起點和終點,它必須響應<=>。如果你想遍歷Range爲好,然後開始對象有向succ迴應:

class OrderedCouple 
    include Comparable 

    def <=>(other) 
    to_a <=> other.to_a 
    end 

    def to_a; [x, y] end 

    def succ 
    self.class[x.succ, y.succ] 
    end 
end 

puts *OrderedCouple[1, 2]..OrderedCouple[5, 6] 
# (1, 2) 
# (2, 3) 
# (3, 4) 
# (4, 5) 
# (5, 6) 
1

試試這個,

def tuples(x, y) 
    return enum_for(:tuples, x, y) unless block_given? 
    (0..Float::INFINITY).each { |i| yield [x + i, y + i] } 
end 

然後,

tuples(1,7).take(4) 
# or 
tuples(1,7).take_while { |x, y| x <= 3 && y <= 9 } 

都返回

[[1, 7], [2, 8], [3, 9]] 
相關問題