···
From: Robert Klemme [mailto:shortcutter@googlemail.com]
# On 10.09.2007 16:52, dblack@wobblini.net wrote:
#
# Ah, ok. I suspected you had some cool usage for this which I
# overlooked and could insert into my repertoire.
irb(main):001:0> require 'with_index'
=> true
irb(main):002:0> a=[1,2,3,4]
=> [1, 2, 3, 4]
irb(main):007:0> i=nil
=> nil
irb(main):008:0> a[i]+=1 until a.all_w_index?{|x,i| x>3}
=> nil
irb(main):009:0> a
=> [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=[1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):011:0> a[i]+=1 while a.any_w_index?{|x,i| x<4}
=> nil
irb(main):012:0> a
=> [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=[1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):030:0> even=nil
=> nil
irb(main):031:0> a[even]+=1 while a.any_w_index?{|x,i| even=i; x%2==0}
=> nil
irb(main):032:0> a
=> [1, 3, 3, 5, 5]
irb(main):033:0> odd=nil
=> nil
irb(main):034:0> a[odd]+=1 while a.any_w_index?{|x,i| odd=i; x%2!=0}
=> nil
irb(main):035:0> a
=> [2, 4, 4, 6, 6]
the idioms would be likened to,
part = nil
machine.repair(part) while machine.any?{|part| part.broken?}
and
broken = nil
machine.repair(broken) while
machine.any?{|part| (broken=part).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
# 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
kind regards -botp