Skip to main content

Posts

Showing posts from December, 2012

Partitioning - or, students into n groups - in Ruby

A while back a friend of mine asked if I could automate the creation of groups in a class of students - to maximize the variation within each group, but minimize the difference between them. This sounded like an interesting problem, so I set about to solve it in my own naive experimental Monte Carlo (inspired) way - without looking into ways this has been solved (surely elegantly) before. The result was this little Ruby script: Loading... First I just require some code I have previously written. (I guess I really should make them into gems or something instead of copying code around...) names.rb  tries to guess sex from a person's name and/or title, and countries.rb  maps countries to continents, regions etc with some fuzzy matching of names. (I'm looking at you Democratic Republic of Kongo,  Koreas  etc.) Easy-peasy. Then I set some standard variables. (Maybe I'll make this dynamic in the future, why not?) The most interesting entry here is the classifiers ...

Unicode characters in irb on OS X

I noticed that my RVM-handled irb in OS X (Mountain Lion) didn't like Norwegian characters today. So instead of an 'ø' , I got '\U+FFC3\U+FFB8' during entry, and nothing afterwards. Like so: Not really satisfactory. After googling: "os x irb unicode characters rvm" I found the answer on stackoverflow . Almost. My adapted solution was this: So now I can do: Better. (Not quite sure why the '--verify-downloads 1' part is needed, but it did the trick.)

Un, deux, tscha-tscha - or Counting in Ruby

Inspired by my little son's eagerness to count when he sees groups of things that (he thinks) can be grouped together these days, I wanted to post my often used, tiny, fairly naïve extension to Ruby's Array class that I call count_by . This might not be the most beautiful way to solve this, but it is fairly readable and is leveraging some key aspects of the Ruby language - open classes, or monkey patching if you must, and dynamic calling of functions. Basically I open up the class Array and add a count_by function to it - that takes as argument the name of the function one wants to count the elements by. The function itself starts off by instantiating a Hash , called map , with default values of 0. For each element in the Array I then call the function by the name provided and increments the  entry in map  corresponding to the result. Like this, if I have a array of, let's say Olympic medalist objects with functions nationality in list , I can ...