DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Trending

  • A Walk-Through of the DZone Article Editor
  • Jeffrey Microscope for Generating Flame Graphs in Java
  • Retesting Best Practices for Agile Teams: A Quick Guide to Bug Fix Verification
  • The Dark Side of Big Data: Pseudo-Science & Fooled By Randomness

Odd Numbers Up To 1..100 In Ruby

By 
Snippets Manager user avatar
Snippets Manager
·
Sep. 08, 06 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
5.4K Views

Join the DZone community and get the full member experience.

Join For Free
// 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 }

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook