From: Robert Klemme [mailto:
[email protected]]=20
# On 10.09.2007 16:52, (e-mail address removed) wrote:
# > I don't think so, but part of the problem for me is that there's no
# > problem -- in other words, I learned that it works with assignment
# > syntax, and probably haven't made all that much use of it but never
# > thought there was any reason for it *not* to work that way.=20
# I suppose
# > it's possible to clobber variables, but then it's possible=20
# to do that
# > without blocks, too, if you're not careful about variable names.
#=20
# Ah, ok. I suspected you had some cool usage for this which I=20
# overlooked and could insert into my repertoire.
irb(main):001:0> require 'with_index'
=3D> true
irb(main):002:0> a=3D[1,2,3,4]
=3D> [1, 2, 3, 4]
irb(main):007:0> i=3Dnil
=3D> nil
irb(main):008:0> a
+=3D1 until a.all_w_index?{|x,i| x>3}
=3D> nil
irb(main):009:0> a
=3D> [4, 4, 4, 4]
note, that i modified #all? so i will know where the trigger was
same also with #any?..
irb(main):010:0> a=3D[1,2,3,4,5]
=3D> [1, 2, 3, 4, 5]
irb(main):011:0> a+=3D1 while a.any_w_index?{|x,i| x<4}
=3D> nil
irb(main):012:0> a
=3D> [4, 4, 4, 4, 5]
but you can do same w scratch vars
though w an added assignment, i find it clearer..
irb(main):029:0> a=3D[1,2,3,4,5]
=3D> [1, 2, 3, 4, 5]
irb(main):030:0> even=3Dnil
=3D> nil
irb(main):031:0> a[even]+=3D1 while a.any_w_index?{|x,i| even=3Di; =
x%2=3D=3D0}
=3D> nil
irb(main):032:0> a
=3D> [1, 3, 3, 5, 5]
irb(main):033:0> odd=3Dnil
=3D> nil
irb(main):034:0> a[odd]+=3D1 while a.any_w_index?{|x,i| odd=3Di; =
x%2!=3D0}
=3D> nil
irb(main):035:0> a
=3D> [2, 4, 4, 6, 6]
the idioms would be likened to,=20
part =3D nil
machine.repair(part) while machine.any?{|part| part.broken?}
and
broken =3D nil
machine.repair(broken) while
machine.any?{|part| (broken=3Dpart).broken?}
so that is,
"repair part while there is any part broken"
vs
"repair broken part while there is any part broken"
your choice.
# As you say, there are many ways to shoot yourself in the foot - block=20
# parameters are just one of them.
Arggh, the scary part is you wont even know if you've been shot until =
you're dead --too late. I myself do not like block args (or any args for =
that matter) clobbering local, global, and instance vars. Surely, it is =
not the intent of the programmer to clobber them, nor is it an intuitive =
intent to peek on arg values from the outside (is that being =
obj-oriented?). I clobber what i clobber. When coding an arg var, surely =
i do not need to bother and question myself "will this var clobber other =
vars?". Ruby should help me on that, not put fear on it. I wonder what =
is the original intent of matz when he designed that feature. It is =
scary. I've been hit by it. And now i have to be careful about naming my =
vars. Is shadowing arg vars really used much in practice? It is not a =
fun part of ruby if you ask me. or maybe, it is just too much fun for =
me. forgive the non-ruby-hacker, pls =20
kind regards -botp