Le 27/5/2005, "Philipp Kern" <trash / philkern.de> a ?crit:
>Dear Ruby fellows,
>
>what is the reason behind the fact that there is no generic coercion
>system apart from the additional overhead?
>
>Concretly I tried to add some ranges. Childish as I am I thought of a
>straightforward way by implementing Range#+:
>
>class Range
>   def +(other)
>     self.entries + other.entries
>   end
>end
>
>However, this does not work on multiple ranges as a temporary array is
>constructed, which does not know of the ability to coerce ranges to arrays.
>
>irb(main):001:0> (?A..?C) + (?a..?c)
>=> [65, 66, 67, 97, 98, 99]
>irb(main):002:0> (?A..?C) + (?a..?c) + (?0..?3)
>TypeError: cannot convert Range into Array
>         from (irb):2:in `+'
>         from (irb):2
>
> From my understanding the conversion should happen automatically when
>coercion is properly implemented. Surely one could just add "to_a" to
>all the ranges, but it certainly made me pondering about it.

I think you probably would be able to create a properly working
addition operator, but you should consider the semantics, as well.
What logical range is represented by (?A..?C) + (?0..?3)? I believe
any range should be characterized by being able to move from start
to end by repeatedly calling #succ.

So you could presumably do something like

def +(other)
  (self.first..other.last)
end

>Kind regards,
>Philipp Kern

E

--
template<typename duck>
void quack(duck& d) { d.quack(); }