From: Robert Klemme Date: 2005-05-30T16:25:21+09:00 Subject: Re: Coercion and ranges Philipp Kern wrote: > Jim Weirich wrote: >> I find it a bit odd that adding two ranges results in an array, but >> assuming that is /really/ what you want, you could indicate a Range's >> willingness to be converted to an array by including a to_ary method. > > Well if I see the range as an array of its elements (which you would > get when you iterate over it), then it's what one might want. Thank > you, that solved it. I thought about to_ary yesterday night, but I > was not aware that it would be called by Array#+. Another probably more efficient variant would be to create a special class that represents sums (= sequences) of Enumerables: class EnumSequence include Enumerable def initialize(*enums) @enums = enums end def each(&b) @enums.each {|e| e.each(&b)} self end def +(enum) @enums << enum self end end class Range def +(r) EnumSequence.new(self,r) end end >> x = (1..10) + (100..101) + (23..25) => # >> x.to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 101, 23, 24, 25] Kind regards robert