David Vallner
2/21/2006 1:19:00 AM
Dna Pondelok 20 Február 2006 14:53 Dirk van Deun napísal:
> I'm a new Ruby user (currently at page 68 of Programming Ruby !) and
> having found something weird, I wonder if either a) "you have already
> found a bug, report it" or b) "yeah, yeah, we all know that this is
> a bit weird, but it is not a problem in practice".
>
> It seems that you can do destructive operations on the minimum element
> of a range, but not on the maximum element (well, you can, but it
> does not have any effect):
>
> irb(main):001:0> rng="a".."z"
> => "a".."z"
> irb(main):002:0> rng.min[0]="b"
> => "b"
> irb(main):003:0> rng.max[0]="y"
> => "y"
> irb(main):004:0> rng
> => "b".."z"
>
> This just doesn't seem right.
>
> Actually this was the second thing I found that doesn't seem right.
> The first was that the first element is shared when you convert
> a range into an array (again, the last one is different):
>
> irb(main):005:0> arr=rng.to_a
> => ["b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
> "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] irb(main):006:0>
> rng.min[0]="c"
> => "c"
> irb(main):007:0> rng.max[0]="x"
> => "x"
> irb(main):008:0> arr
> => ["c", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
> "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>
> This is really dirty, but at least this was to be expected from the
> specifications ("All you need to be able to make ranges is 'succ' and
> '<=>'" -- there is no talk of a deep copy as a requirement.)
>
Range code seems to enumerate and determine the maximum by generating all
successors lesser or equal, or lesser than the Range endpoint. For these
examples to "work", it would also require to check whether the last generated
element is equal to the endpoint, and return the endpoint object if it was.
That said, I think this situation is similar to the one with String keys in a
hash. Where immutable objects would be enforced otherwise, Ruby gives you the
responsibility for if you choose to change them. Maybe this behaviour should
instead be documented as with the Hash class, if it isn't already; I can't
imagine where this could only be worked around with a noticeable kludge.
David Vallner