Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Odd numbers up to 1..100 in Ruby

// 10 different ways to display odd numbers 1 through 100 in Ruby

   1  
   2  100.times do |i|
   3    next if i % 2 == 0
   4    puts i
   5  end
   6  
   7  50.times { |i| p i*2+1 }
   8  (1..100).step(2) { |i| puts i}
   9  1.upto(100) { |i| puts i unless i[0].zero? }
  10  puts Array.new(50) { |i| i * 2 + 1 }
  11  # a self referential recursive lambda :-)
  12  lambda { me = lambda { |x| p x; me.call(x+2) if x < 99 } ; me.call(1) }.call
  13  
  14  # same thing, but passing the lambda around
  15  rec = lambda { |v,l| p v; l.call(v+2,l) if v < 99 }
  16  rec.call(-1,rec)
  17  
  18  # same recursive algorithm, but in method form
  19  def odds(x=1)
  20    p x
  21    odds(x+2) if x < 99
  22  end
  23  odds
  24  
  25  class Integer
  26    def odd?
  27      self[0].nonzero?
  28    end
  29  end
  30  100.times { |i| puts i if i.odd? }
  31  
  32  
  33  require 'delegate'
  34  class OddNum < DelegateClass(Fixnum)
  35    def initialize(value)
  36      value |= 1  # force it odd
  37      super(value)
  38    end
  39    
  40    def succ
  41      # note that the delegated succ gets called when we call super
  42      # and the constructor forces it (up) to the next odd number
  43      OddNum.new(super)
  44      
  45      # or
  46      # OddNum.new(self + 1)  # still using the constructor's force to odd
  47      # or 
  48      # OddNum.new(self + 2)  # being odd all on our own
  49    end
  50  end
  51  (OddNum.new(1)..100).each { |i| puts i }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS