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

Odd numbers up to 1..100 in Ruby (See related posts)

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

100.times do |i|
  next if i % 2 == 0
  puts i
end

50.times { |i| p i*2+1 }
(1..100).step(2) { |i| puts i}
1.upto(100) { |i| puts i unless i[0].zero? }
puts Array.new(50) { |i| i * 2 + 1 }
# a self referential recursive lambda :-)
lambda { me = lambda { |x| p x; me.call(x+2) if x < 99 } ; me.call(1) }.call

# same thing, but passing the lambda around
rec = lambda { |v,l| p v; l.call(v+2,l) if v < 99 }
rec.call(-1,rec)

# same recursive algorithm, but in method form
def odds(x=1)
  p x
  odds(x+2) if x < 99
end
odds

class Integer
  def odd?
    self[0].nonzero?
  end
end
100.times { |i| puts i if i.odd? }


require 'delegate'
class OddNum < DelegateClass(Fixnum)
  def initialize(value)
    value |= 1  # force it odd
    super(value)
  end
  
  def succ
    # note that the delegated succ gets called when we call super
    # and the constructor forces it (up) to the next odd number
    OddNum.new(super)
    
    # or
    # OddNum.new(self + 1)  # still using the constructor's force to odd
    # or 
    # OddNum.new(self + 2)  # being odd all on our own
  end
end
(OddNum.new(1)..100).each { |i| puts i }

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts