Code Club: Ruby Week 1

So my coworker Ben and I keep trying to keep people interested in learning and tinkering with languages.  So far we’ve explored python, scala, and f#.  Scala and F# seemed to have scared off most of our attendees, so we’re trying to reign it back into the mainstream by exploring Ruby.  For this first week, attendees are to do whatever Euler problems they are comfortable doing, as long as they do them in Euler.

Since I’ve done the first 20 or so Euler problems in all of the above languages, I was able to power through the first ten problems in Ruby pretty quickly.  I also used the opportunity to mess around with mercurial.  I originally wanted to use git and github, but the windows version of git is fairly opaque to me.  I set up an online repository for my Ruby exploration on intuxication. You can peer through the repository here: http://mercurial.intuxication.org/hg/rubyeuler/

I can’t wait until Wednesday to share how clever I feel, so I’m going to share a couple snippets that I feel especially pleased about.

maxprod = 0
999.downto(100) {|i| 
  999.downto(100) {|j|
    maxprod = [i * j, maxprod].max if ((i * j).to_s == (i * j).to_s.reverse)
  }}
puts maxprod

The whole creating an array of two items to grab the maximum is cool, but the if statement negating the previous expression makes things simultaneously easier to read and confusing to my traditional Java brain.

class Array
  def prod
    inject do |prod,x| prod ? prod * x : x end
  end
end

n = 2
arr = []

while (n <= 20)
  currn = n
  arr.each {|i| currn /= i if currn % i == 0}
  arr << currn
  n+=1
end

puts arr.prod

The real “wow” moment I had here was the fact that you could extend existing classes without actually creating a whole new class. “Redefining” a class just adds/overwrites the things that you put in your newly written class definition. Totally blew my mind.

Leave a Reply

Your email address will not be published. Required fields are marked *