---2049402039-103646226-1164557367=:12154
Content-Type: MULTIPART/MIXED; BOUNDARY="-2049402039-103646226-1164557367=:12154"
This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools.
---2049402039-103646226-1164557367=:12154
Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed
Content-Transfer-Encoding: QUOTED-PRINTABLE
Hi --
On Mon, 27 Nov 2006, James Edward Gray II wrote:
> On Nov 26, 2006, at 9:53 AM, wrote:
>
>> On Mon, 27 Nov 2006, James Edward Gray II wrote:
>>=20
>>> On Nov 26, 2006, at 8:54 AM, Olivier wrote:
>>>=20
>>>> Le dimanche 26 novembre 2006 15:00, Josselin a =E9crit :
>>>>>=20
>>>>> array.index(array.detect {|x| x > 0}) =3D> 15
>>>> c =3D 0
>>>> array.each{|v| break if not v.zero?; c +=3D 1}
>>>> puts c # =3D> 15
>>>=20
>>>>> result =3D array.enum_with_index.find { |n, i| n.nonzero? }.last resc=
ue=20
>>>>> nil
>>=20
>> That seems kind of like a reinvention of Array#index, though. It also
>> has the usual problem with rescue, i.e., that you might rescue the
>> wrong thing (if nonzero? is mistyped or whatever). Do you see an
>> advantage to doing it this way, rather than the index/detect way?
>> (I'm being lazy and not benchmarking them....)
>
> Well, it only walks the Array once. The other way walks it once for dete=
ct()=20
> and again for index(). I agree that it's not sexy code though.
>
> I believe there has been talk in the past of having index() take a block =
for=20
> matching. That would solve this problem ideally. I can submit an RCR if=
=20
> people think it's worth it, but I'm pretty sure Matz said it was OK last =
time=20
> it came up... (Correct me if I am wrong!)
Yes, there's an accepted RCR for it. That will be good.
This exchange relates to something I've been pondering for a while,
namely: is there always (or very, very often) an inverse relation
between elegance of code and efficiency? I don't mean to sound like
I'm singling out your example -- on the contrary, it seems that over
and over we see cases where a nice concise solution bombs out compared
to one that's longer, possibly less clear (I still can't read the
enum* stuff as quickly and confidently as I can read the regular
Enumerable stuff, though that may just be due to stupidity), but
faster.
I haven't really documented or studied this in detail, though it does
seem to keep happening. It might be interesting to look into further.
David
--=20
David A. Black |
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1]
http://www.manning.com/black | [3]
http://www.rubypowerandlight.com
[2]
http://dablog.rubypal.com | [4]
http://www.rubycentral.org
---2049402039-103646226-1164557367=:12154--
---2049402039-103646226-1164557367=:12154--