Pascal vs. Ruby

29 06 2009

On ruby-talk somebody was asking for a method which will be used to generate a random string, by returning either a lowercase letter or one of the digits 0-9 when called. As an example he posted the following Pascal program:

function GetRandomChar: char;
var
 r: integer;
begin
 r := random(36);
 case r of
   0..25: result := chr(ord('a') + r);
   else : result := chr(ord('0') + r);
 end;
end;

“Translating” this to Ruby, this is what I got:

In your face, Niklaus Wirth! ;-)

P.S. Actually I do have fond memories of the good old Turbo Pascal days.


Quick and dirty lazy lists in Ruby

18 06 2009

Hash.new with a block is a sexy beast: you can specify default hash values and when a key is first used, the value will be calculated and inserted into the Hash. Based on that behavior I took a couple of minutes to hack together a small proof of concept class for lazy lists:

As I said, this is quick and dirty, especially since you have to pass the entire Hash.new block to LazyList.new right now. Other than that I quite like it though. I know there are at least two other lazy list implementations for Ruby, but it seems like both haven’t been updated in a while and I don’t particularly like their interfaces. Dunno, if I manage to simplify list definition, I may actually try to develop this into something. Don’t hold your breath though…


Unsavory updates

16 06 2009

Today I felt like playing around with unsavory a bit more, which led to some minor improvements:


  • code reorganization: the delicious class got moved to a separate file in lib/ and got a new method for easier retrieval of the URLs array

  • login credentials can now be read from a config file, thus making HighLine optional


Next on my list is packaging this up as a gem so people can simply install it with ‘gem install unsavory’.


Review: The Well-Grounded Rubyist (Manning Publications)

09 06 2009

As part of Rubylearning’s current book promotion I’m reading The Well-Grounded Rubyist by David A. Black. Here are my thoughts on the book:

If you are new to Ruby, this may very well be the book you are looking for, since the author was really serious about the “well-grounded” in the title. Together the first six chapters form Part 1, aptly called “Ruby Foundations”. Here you’ll learn about objects, modules, classes, self and control-flow techniques. Although this part may not be the most interesting for more experienced Rubyists, it’s certainly well-written and manages to present a lot of very fundamental Ruby right at the beginning. True, at first I was a bit surprised to see that singleton methods were – implicitly – introduced before classes, but when you follow the author’s logic, it all makes a lot of sense. What I really like about this approach is that it exposes the reader to concepts needed for some quite advanced Ruby coding right away, and in a very light-hearted and “natural” manner. Well done!

Part 2 (“Built-in classes and modules”) covers everything from strings, over symbols to regular expressions and file I/O. What I really like about this part is that the author dedicated two whole chapters to collections and iterators/enumerators, which are essential for everyone striving to become fluent in Ruby.

Last but not least Part 3 (“Ruby dynamics”) talks about singleton methods, procs, lambdas, Symbol#to_proc, the various eval methods, bindings and introspection, thus equipping the reader with all the necessary tools for metaprogramming, one of the many things that make Ruby that sexy little beast it is.

Oh yeah, since I didn’t mention this before, “The Well-Grounded” Rubyist” covers Ruby 1.9.1, which means you’ll learn about the coolest Ruby around. Don’t worry though, most of what you read will also apply to 1.8.6, but isn’t it about time that we all slowly moved on?


Fitness galore

07 06 2009

Since my trip last year I have been fitter than I’ve been for ages, thanks to a weight-loss of about 25kg, more exercise and a healthier diet. Through kyrah’s tweets I learned about a workout program called one hundred pushups and decided to have a closer look today. I took the initial test and only managed a meager 12 good-form pushups, but they were always one of my weak spots. At least I start from the most challenging category. Through the site I also found the two related programs two hundred situps and two hundred squats, where the initial tests looked a lot friendlier: with 35 situps and 40+ squats both programs suggest that I start from week 3. :-)

Now let’s see how effective these workouts will turn out to be.


unsavory — get rid of stale Delicious bookmarks

06 06 2009

While browsing through my Delicious bookmarks the other day, I realized that over time I had accumulated quite a few dead links (about 5% of my collection). I then looked for a simple tool to automatically remove them, but couldn’t find one that appealed to me, so I wrote my own script called unsavory which you can find on GitHub:

http://github.com/citizen428/unsavory/tree/master

It uses HTTParty to generate a list of all your bookmarks, which then get checked individually with Net::HTTP. Every link that returns an HTTP status code of 404 will automatically be removed (no questions asked, no undo), links with a status code other than 200 (OK) won’t be changed but will display some information in case you want to fix them manually. Here’s some example output (links anonymized for this post):

  Enter Delicious username: citizen428
  Enter Delicious password: *********

citizen428 has 664 bookmarks. Processing URL #0001: OK Processing URL #0002: OK Processing URL #0003: OK Processing URL #0004: OK Processing URL #0005: OK ... Processing URL #0013: 405: http://... ... Processing URL #0074: 302: http://... ... Processing URL #0086: Connection reset by peer – https://...

Not bad for under 60 lines of code. :-) I hope this is useful to some of you, I do have some features I plan on adding to this in the future.


Review: Functional Programming with Clojure (PeepCode screencast)

25 05 2009

A couple of month ago I first heard about Clojure, a Lisp-like language sitting on top of the JVM. Alas I didn’t yet have time to have a closer look at it, so I decided to get myself the PeepCode screencast.

This 65 minute video is the first to use PeepCode’s new post-production workflow, and it’s very well done! In just a little over an hour you go from learning about Clojure’s basic concepts and syntax to writing a multi-user text based adventure game, tackling topics such as data structures, thread safety, lazy collections, unit testing and packaging of Clojure apps. All of that is clearly presented and easy to follow, which makes for an ideal first overview of the language. If you are curious about Clojure but have little time, consider investing the money for this screencast!

On a more general note it’s interesting to see that more and more languages seem to target the JVM. I never really had any interest in Java and also totally ignored Groovy, but now that JRuby, Scala and Clojure entered the stage, I might start looking into the Java platform a bit more. Especially Scala with its mixed Ruby/Haskell feel appeals to me, but as antifuchs showed, there’s also pretty neat stuff (GitHub project) one can do with Clojure.


Most used shell commands

25 05 2009

I recently found a bash snippet which creates a list of the commands in your .bash_history file and how many times you invoked them:

history | awk '{a[$2]++ } END{for(i in a){print a[i] " " i}}'|sort -rn|head

Although there was no real point in doing so, I felt the need to write a short Ruby script to do the same:

Here’s the output on my MacBook:

$ command_stats | head
time: 75
cd: 68
ls: 66
git: 35
cat: 32
irb: 20
awk: 17
ruby: 15
scala: 15
vim: 12

If you are surprised by how many times (no pun intended) I called time, it’s just because I was benchmarking Project Euler solutions in several languages, everything else is quite regular (and suggests I don’t use the Finder much ;-) ).


Review: Meet MacRuby (PeepCode screencast)

24 05 2009

This afternoon I had the time to finally watch the PeepCode Meet MacRuby screencast.

In case you don’t know MacRuby, it’s a Ruby interpreter sitting on top of Objective-C and OS X core technologies (see also here).

During the 74 minute screencast you will build a basic but functional Twitter client, and in the process learn about MacRuby and Cocoa basics, using Xcode and InterfaceBuilder to develop and bundle your application and many other interesting topics.

The screencast is very well structured, easy to follow and full of good and practical information, including perks and rough edges of the current MacRuby version. All in all a really enjoyable and informative video, which is well worth US$9 (or less if you buy packs of credits)!


Review: Ruby in Practice (Manning Publications)

18 05 2009

I read Ruby in Practice for the upcoming book promotion on RubyLearning, and I have to say it’s a pretty neat book which will be well worth your time and money. Over the course of 360 pages Jeremy McAnally and Assaf Arkin tackle lots of different topics of interest to developers. The book is structured in 3 main parts:

  • Ruby techniques: Gives a general introduction to Ruby’s strength (which sometimes reads as a bit of a sales pitch), BDD and TDD, as well as scripting with Ruby (including OLE and OSA).
  • Integration and communication: This part covers Rails, web services in general (HTTP, REST, SOAP), automating communication with email and IM, asynchronous messaging and deployment options.
  • Data and document techniques: This part talks about databases, structured text, authentication, searching, indexing and document processing.

Chapters usually present the reader with a problem, then show an example solution which usually makes good use of existing libraries and then finish with further discussion on the topic (alternative ways to implement it, pitfalls in using the shown solution in “real life” scenarios etc.). For people with previous knowledge of Ruby this book is a good read, which shows how the dynamic nature of the language combined with the quite big amount of readily available libraries enable developers to quickly and efficiently find solutions to common problems. I sometimes do have minor quirks with some of the code, but that’s just personal preferences and being nitpicky. All in all it’s a very solid book which I enjoy quite a lot.


Create your own (Ruby) API browser in 3 easy steps

17 05 2009

  • Step 1: Download Fluid, an awesome little application to create site specific browsers.
  • Step 2: Find some online API documentation. For Ruby I recommend railsapi.com or RubyBrains.
  • Step 3: Create your app in Fluid:
  • Fluid

Here’s an example screenshot of a site specific browser for RubyBrain.com:

Fluid RubyBrain

Of course this still requires you to have a working internet connection, but you could always use a local version of the API docs when creating the app. On a related note you should also check out Goo which is a nice alternative to gem server on OS X.


A TextMate command for the RubyLearning forums

10 05 2009

As we all know posting code to Moodle (the software that powers RubyLearning) can be a bit cumbersome. I therefore created a TextMate command which will

  • take the currently active file
  • replace all occurrences of < with the HTML-entity
  • wrap all of that in [code ruby] tags and
  • copy it to the clipboard, ready to be pasted into the forums.

Source:

Download:
RubyLearning.tmCommand


I'm in your Pi, crunching your numbers ;-)

03 05 2009

From Ruby Quiz #202:

And sometimes the fastest code is the code you don’t write. Michael Kohl’s solution:

require ‘rubygems’
require ‘hpricot’
require ‘open-uri’

doc = Hpricot(open(‘http://www.eveandersson.com/pi/digits/100000’))
puts (doc/‘pre’).inner_html

It finishes in less than one second for the entire 100,000 digits!

And no, this wasn’t a serious submission… :-)


Clever documentation

26 04 2009

Playing with Squeak‘s Method Finder, I discovered a really neat feature that I wish would be available for Ruby documentation. Here’s the description from the built-in help:

[...] use an example to find a method in the system. Type receiver, args, and answer in the top pane with periods between the items. 3. 4. 7

Yes, this means that if you want to know how to do modulo in Smalltalk, you can open the Method Finder, type 7. 3. 1 and see that the answer is Number>>\\, whereas ‘abc’ . ‘ABC’ will tell us about String>>asUppercase.


Reading frenzy

23 04 2009

Since my reading time wasn’t influenced by distracting things like work or studies last year, I managed to read 69 books since end of April 2008, which quite likely is a new personal record for one year. Here’s the complete list, some of this books I had wanted to read forever, some others were just lucky finds and yet others were just…finds. ;-)

Marion Molteno: “A Language in Common”
James Frey: “A Million Little Pieces”
Haruki Murakami: “After Dark”
Haruki Murakami: “After the Quake: Stories”
Ali Smith: “Ali Smith’s Supersonic 70s”
Lewis Carroll: “Alice’s Adventures in Wonderland”
Neil Gaiman: “American Gods”
Heinrich Böll: “Ansichten Eines Clowns”
Anita Desai: “Baumgartner’s Bombay”
Achmat Dangor: “Bitter Fruit”
Monica Ali: “Brick Lane”
Heinz Peter Schwerfel: “Buenos Aires intensiv.: Tango urbano – Stadt im Aufbruch”
Ines Rieder: “Cosmopolis: Urban Stories by Women”
Andrea Camilleri: “Der Hund aus Terracotta”
Peter Handke: “Die Angst des Tormanns beim Elfmeter”
Thomas Mann: “Die Betrogene. Erzählungen 1940 – 1953.”
Helge Schneider: “Die Memoiren des Rodriguez Fazantas”
Stanislaw Lem: “Eine Minute der Menschheit.”
Orson Scott Card: “Ender’s Game”
Terry Pratchett: “Equal Rites”
Jonathan Safran Foer: “Everything Is Illuminated”
Feridun Zaimoglu: “German Amok.”
Terry Pratchett & Neil Gaiman “Good Omens”
Haruki Murakami: “Hard-Boiled Wonderland and the End of the World”
Irvine Welsh: “If You Liked School, You’ll Love Work”
Andre Brink: “Imaginings of Sand”
Orhan Pamuk: “Istanbul”
Gene Brewer: “K-Pax”
Haruki Murakami: “Kafka on the Shore”
Peter Handke: “Kali”
Feridun Zaimoglu: “Leinwand”
Yann Martel: “Life of Pi”
William Golding: “Lord of the Flies”
Elfriede Jelinek: “Lust”
Ryszard Kapuscinski: “Meine Reisen mit Herodot”
Saul Bellow: “Mosby’s Memoirs and Other Stories”
Howard Marks: “Mr. Nice: An Autobiography”
Orhan Pamuk: “My Name Is Red”
Eli Gottlieb: “Now You See Him: A Novel”
John Steinbeck: “Of Mice and Men”
Amit Gilboa “Off the Rails in Phnom Penh”
Terry Pratchett: “Pyramids”
Paul Torday: “Salmon Fishing in the Yemen”
Woody Allen: “Side Effects”
Miriam Tzali: “Soweto Stories”
Helen Oyeyemi: “The Icarus Girl”
John Updike: “Terrorist: A Novel”
Jorge Luis Borges: “The Aleph”
Zadie Smith: “The Autograph Man”
Alex Garland: “The Beach”
Iain M. Banks: “The Crow Road”
John Case: “The Eighth Day”
Paul Theroux: “The Elephanta Suite: Three Novellas”
Shan Sa: “The Girl Who Played Go”
Leon Uris: “The Haj”
Michael Cunningham: “The Hours”
Miguel de Cervantes: “The Jealous Extremaduran”
Terry Pratchett: “The Last Continent”
A. B. Yehoshua: “The Lover”
Ernest Hemingway: “The Old Man and The Sea”
M. C. Beaton: “The Quiche of Death”
Audrey Niffenegger: “The Time Traveler’s Wife”
Roddy Doyle: “The Van”
H.G. Wells: “The War of the Worlds (Penguin Classics)”
Iain M. Banks: “The Wasp Factory: A Novel”
Aravind Adiga: “The White Tiger: A Novel”
Terry Pratchett: “Thud!”
Zadie Smith: “White Teeth: A Novel”
Florian Weber: “You’ll Never Walk Alone. Ein Fußballmusikroman”

And that’s the 2 books I’m currently reading:

Nancy L. Clark: “South Africa: The Rise and Fall of Apartheid”
Will Ferguson: “Hokkaido Highway Blues”