Tag Archives: programming

Multiple returns in Ruby

Oh ruby, how beautifully simple you make multiple returns….

def add_and_subtract(v1,v2)
   return (v1 + v2),(v1 - v2)

print "Input a number: "
in1 = gets.to_i
print "Input another number: "
in2 = gets.to_i

result = add_and_subtract(in1,in2)
print "#{in1} + #{in2} = #{result[0]}n"
print "#{in1} - #{in2} = #{result[1]}n"

Generating N colors (Ruby)

Kevin messaged me a few days ago to give me a problem his boss had given him. Generate a list of colors that can be used when drawing n lines on a graph.  My first solution was to just pick 20 or 30 colors, put them an in a list and pick one of them for each graph, but I had a few other ideas.  One of them seemed stupidly-simple, so I threw it together in ruby and had it generate an html page to display the results.

maxColors = 250
File.open('colors.html', 'w') do |myfile|  #create file
    myfile.print "nnn"
    1.upto(maxColors) { |tblcnt|
        myfile.print "n"
        1.upto(tblcnt) { |rowcnt|
            newColor = (rowcnt * (0xFFFFFF/tblcnt)).to_s(16)
            myfile.print "n"
        myfile.print "
n" } myfile.print " nn" end

Here are the results from my code:

Click for html (warning 1MB file)

Click for html (warning >1MB file)

The code basically takes 0xFFFFFF, divides it by n and displays each color.  It’s a simple hack, but the patterns it generated were just incredible.  Most of the color lines aren’t distinct enough to use in graphing, so it doesn’t really match what Kevin asked me to do.  Oh well, it was a fun little script to write.

KHAN! (Ruby)

This evening I read a story on reddit in which someone graphed the number results google gives vs. the number of A’s in “KHAN.”  KHAN! is from the second Star Trek Movie, “The Wrath of Khan.”  The original results from that article are here.  I thought it was pretty funny, so I decided to write a ruby script to automatically do the same thing (I’ve been using ruby a lot lately).

require 'gruff'
require 'open-uri'

dataToGraph = Array.new
khanNumOfAs = 1
maxKhanAs = 100

g = Gruff::Line.new
g.title = "KHAN!"

    sleep 0.5
    open('http://www.google.com/search?q=KH' + "A"*i + "N") do |f|
        f.each do |line|
            dataToGraph[i] = $~[1].gsub(/,/, "").to_i if /of about ([0-9,]+)/.match(line)
    print "KH#{"A"*i}N!!!!!    results: #{dataToGraph[i]}n"
g.data("KHAN!", dataToGraph)

Kevin helped me with the regular expressions to get the number of results out of google.

Final results, no log scale :-(

Final results, no log scale 🙁