From: "David A. Black" Date: 2009-06-24T02:35:37+09:00 Subject: Re: Is it the ruby way to implement #downto --1926193751-1036515482-1245778524=:23145 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1036515482-1245778524=:23145" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1036515482-1245778524=:23145 Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8BIT Hi -- On Wed, 24 Jun 2009, Skye Shaw!@#$ wrote: > On Jun 23, 8:36�am, Li Chen wrote: >> Hi all, >> >> I wonder if the following code is the ruby way to implement >> Integer#downto. >> ####################### >> class Integer >> � def my_downto(final=2) >> � � for i in (final..self).to_a.reverse >> � � � yield i >> � � � end >> � �end >> �end >> >> �10.my_downto(-1) do |i| puts i end > > Well, I'd hope that creating 3 unnecessary objects wouldn't be deemed > the Ruby way :^) > Most code I've seen would use each() instead of for i in (). Each is > faster anyways. > > Why not use the bastardized C way: > > class Integer > � def my_downto(final=2) > i = self > while i >= final > yield i > i-=1 > end > end > end > > I don't believe the Ruby community has shunned the idea of writing C > in ruby have they? I think most of us shun doing the heavy lifting when Ruby can do it for us :-) There's nothing C-specific about using an explicit loop variable, but it's pretty uncommon in Ruby code, except when doing exercises like implementing each without recourse to each and things like that. I'd be tempted to do something like: def my_downto(n) (self-n+1).times {|x| yield self-x } self end I don't know how it performs compared to the others. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com --1926193751-1036515482-1245778524=:23145-- --1926193751-1036515482-1245778524=:23145--