Is it the ruby way to implement #downto

Hi all,

I wonder if the following code is the ruby way to implement
Integer#downto.

Thanks,

Li

#######################
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

On Jun 23, 8:36 am, Li Chen [email protected] wrote:

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?

-Skye

Skye Shaw!@#$ wrote:

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.

I do it this way using each().

def my_downto2(final=2)
(final…self).to_a.reverse.each do |i| yield i end
end

But I am still uncomfortable that I have to use #to_a followed by
#reverse to do the trick. Besides using while loops what is the best way
to add a new method of #downto?

Thanks,

Li

Hi –

On Wed, 24 Jun 2009, Skye Shaw!@#$ wrote:

   end
Why not use the bastardized C way:

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 :slight_smile: 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

Hi –

On Wed, 24 Jun 2009, Li Chen wrote:

end

But I am still uncomfortable that I have to use #to_a followed by
#reverse to do the trick. Besides using while loops what is the best way
to add a new method of #downto?

def my_downto(n)
(-self…-n).each {|i| yield -i }
self
end

:slight_smile:

David

David A. Black wrote:

def my_downto(n)
(-self…-n).each {|i| yield -i }
self
end

:slight_smile:

David

Hi David,

Thank you so much,

Li