Is it the ruby way to implement #downto

L

Li Chen

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
 
S

Skye Shaw!@#$

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?

-Skye
 
L

Li Chen

Skye said:
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
 
D

David A. Black

Hi --

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?

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

:)


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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top