My First Ruby Program

In danger of seeming to jump on the bandwagon, I’ve spent part of my afternoon writing my first Ruby program. First off — does this mean I’m leaving Python behind? No. Hey, it’s an up-and-coming language that seems to be catching on. I know quite a few people doing Rails stuff. So why not see what the fuss is about?

I think everyone has their own little pet problem they try to solve with a new programming language. Mine is the Sieve of Eratosthenes, which is an easy enough concept to remember yet complex enough so you have to dig a bit deeper into arrays, etc, then a normal tutorial.

This little script accepts a command-line argument for the maxium number. If it can parse that to a string, or no argument is given, it uses 20. My first thoughts are below:

#!/usr/bin/ruby

if ARGV[0] and ARGV[0].to_i>0
  Max=ARGV[0].to_i
else
  Max=20
end

puts “find primes from 1 to “+Max.to_s
nums = Array.new
primes=Array.new
composite=Array.new

for x in 2..Max
    nums.push(x)
end

nums.each do |x|

   if not composite.find{|i| i==x}
      primes.push(x)
      composite+=nums.find_all{|i| i>x && i%x==0}
  end

end

puts primes
  • I think the find and find_all methods for Enumerations should be easier to do if you want to do something easy — say, just find a value in an array.
  • I really like the unified object approach. It seems that all basic objects have .to_s and most have .to_i.
  • One of my attempts was to used a step in range, but that seemed little weird. Luckily, find_all did it for me.
  • It seemed silly that I had to populate the nums array at all. I’m sure that someone else will show me something better.

Overall, I’m impressed. I expected sometime Perl-ish but instead got something quite a bit different. And better, I do believe. I’m also sure that others will find better ways to do this — let me know if you have something.

4 Responses to “My First Ruby Program”

  1. jimweirich Says:

    It seemed silly that I had to populate the nums array at all. I’m sure that someone else will show me something better

    I don’t see you changing nums at all, so perhaps just:

    nums = (2..Max)

    Would be all you need.

  2. Mike Says:

    Yeah, I thought if I did a Ruby post I could get Jim to comment.

    I took out nums completely and replaced

    nums.each do |x|

    with

    for x in 2..Max

    I thought I tried this before and it didn’t work — but it was probably something else that was wrong.

    Thanks Jim!

  3. Glenn Vanderburg Says:

    As for find … for your first use of find I would write this:

    if not composite.include? x

    or maybe

    unless composite.include? x

  4. Mike Says:

    Cool Glenn — I didn’t know arrays had an “include” method — that makes things easier.

    The “new” version, using Glenn’s and Jim’s changes are one second faster than the original, using the first 600 integers.

Leave a Reply

You must be logged in to post a comment.