Menu Sidebar
Menu

Avdi Grimm

Hacker; code documentarian.

Janko Marohnić on Roda

Ok, so far this looks like a flavor of Grape with a weird syntax. But the difference is that the route block is called each time a request is made, so this routing is actually happening in real-time. This means that you can handle the request while you’re routing it. And this is where it gets cool.

I like articles that show what differentiates one tool from others, and this one does a fine job.

We talked to Jeremy Evans about Roda on Ruby Rogues a little while back.

Hello, Crystal

Here’s an anagram-finding program in Ruby:

table = Hash.new { |h,k|
  h[k] = []
}
IO.foreach("/usr/share/dict/words") do |line|
  word = line.chomp
  key  = word.downcase.chars.sort.join
  table[key] << word
end

word     = ARGV[0].downcase
anagrams = table[word.chars.sort.join]
anagrams.map!(&:downcase)
anagrams.delete(word)
if anagrams.any?
  puts "Anagrams for '#{word}': #{anagrams.join(", ")}"
else
  puts "Sorry, no anagrams for '#{word}'"
end

Here’s the same program, but in Crystal:

table = Hash(String,Array(String)).new { |h,k|
  h[k] = [] of String
}
File.each_line("/usr/share/dict/words") do |line|
  word = line.chomp
  key  = word.downcase.chars.sort.join
  table[key] << word
end

word     = ARGV[0].downcase
anagrams = table[word.chars.sort.join]
anagrams.map!(&.downcase)
anagrams.delete(word)
if anagrams.any?
  puts "Anagrams for '#{word}': #{anagrams.join(", ")}"
else
  puts "Sorry, no anagrams for '#{word}'"
end

See if you can spot the differences (there are exactly four).

Here are some benchmarks:

$ time ruby anagrams.rb avdi
Anagrams for 'avdi': avid, diva

real    0m0.621s
user    0m0.597s
sys     0m0.020s
$ crystal build --release anagrams.cr
$ time ./anagrams avdi
Anagrams for 'avdi': avid, diva

real    0m0.230s
user    0m0.305s
sys     0m0.017s
Newer Posts
Older Posts

Virtuous Code

"The three virtues of a programmer: laziness, impatience, and hubris" — Larry Wall

Books and Screencasts

RubyTapas Screencasts

RubyTapas Screencasts

Small plates of gourmet Ruby code.

Confident Ruby

Confident Ruby cover

32 Patterns for joyful coding.

The Making of Cowsays.com

Confident Ruby cover

Watch me build an app in Sinatra and Rails

Objects on Rails

Objects on Rails

A developer notebook on applying classic Object-Oriented principles to Ruby on Rails projects.

Exceptional Ruby

Exceptional Ruby

The definitive guide to exceptions and failure handling in Ruby.

Archives

Categories