Archive for the ‘ruby’ Category

Blog Bifurcation

Saturday, May 31st, 2008

One of the reasons I haven’t been blogging much lately is because I’ve decided to bifurcate my blog into a professional/technical blog (which will continue here on lojic.com/blog) and a personal blog, and until I’ve decided on the technology to use for my personal blog I’ve been reluctant to blog much.

The motivation for the split is the feeling that a lot of my non-technical family & friends grow weary of weeding through a lot of techno-geek material to find anything interesting, and folks who read my blog for technical info probably don’t want to weed through the silly videos, etc.

Wordpress has worked fine for my blog thus far, but I want to take the opportunity to develop my personal blog in a new technology more for the learning experience than necessity. I haven’t had time to select the appropriate technology, so I have a bit of analysis paralysis.

The candidates are:

  • Ruby on Rails: I currently develop primarily in Ruby on Rails, so in that respect it would be the logical choice and easiest way to get started; however, it wouldn’t have the benefit of learning a new technology.
  • Arc: I had high hopes for Arc when Paul Graham first released it. I still think it has potential, but that potential is limited by Paul’s interest level and available time. It’s been over 3 months since the last release and that was only a small incremental improvement. The forum seems dead, and the fact that Arc went through a 5 year blackout period makes me wonder whether it will be a dead-end language and a waste of valuable time.
  • Common Lisp: I am leaning toward a Lisp, so if Arc doesn’t pan out, Common Lisp would be a good fallback language. It’s much more mature with robust implementations. It doesn’t provide a nice batteries included experience though, and I’ve been reluctant to collect the necessary libraries from various sources to allow anything remotely similar to Ruby on Rails with respect to ease of development. I think it may have a greater long term potential though, so it may be worth the effort.
  • Scheme: The PLT web server may give me a head start on a Lisp based web site, and Arc is based on MZScheme, so it’s on the short list.
  • Haskell: I know very little Haskell (even less than Lisp which is not much), but I’m intrigued by many aspects of the language. GHC seems to be a great compiler that produces well performing programs. My initial impression is that it will take more effort to learn than a Lisp, but in terms of brain stretching, it has a lot to offer. There is a Haskell based web server available, but like a lot of fringe languages, it appears to be pretty rough around the edges.

I have a vacation coming up, so I think I’ll use some of the down time to do some research and make a decision. Look for the blog bifurcation to happen in the latter half of June. If you have any opinions on the matter, please add a comment :)

2008 Programming Language Plan

Thursday, January 17th, 2008

I’ve learned a number of programming languages since I began programming 25 years ago. Earlier in my career, my choice of which programming language to learn was largely driven by external factors such as a class or job requirement, or the expectation of job demand in the future.

More recently I’ve enjoyed learning new programming languages both for the joy of learning something new, and for an increase in productivity.

While it’s true that no programming language is a silver bullet, I’ve found that the choice of programming language can provide a dramatic increase in productivity - much more so than many have asserted. The benefit can be direct, by allowing the creation of a solution to a particular problem with less time and effort than it would take using another language, or it can be an indirect by providing new ways to think about a solution.

Do you think language affects how we think?

The Past

In 1982, I spotted a Radio Shack Color Computer in a store window and immediately applied for a Radio Shack credit card which had a credit limit ($500) sufficient to purchase the computer which had 4K of RAM (I later upgraded to 16K) and no external storage (unless you count the ability to hook up a cassette recorder). Contrast the 16K RAM of that early machine with my current 2,097,152K RAM :)

That was the beginning of a life long interest in programming.

In the language list below, bold indicates a more significant professional involvement, and the year indicates when I first learned the language. I’ve also likely forgotten a few:

  1. 1982 - Radio Shack Extended Color BASIC
  2. 1983 - 6809e Assembler
  3. 1983 - Pascal
  4. 1984 - HP 48SX RPL
  5. 1984 - S/360 Assembler
  6. 1985 - COBOL
  7. 1985 - dBase III / Metafile
  8. 1985 - C
  9. 1985 - 8088/8086 Assembler
  10. 1986 - C++
  11. 1996 - Java
  12. 1997 - Perl
  13. 2002 - C#
  14. 2004 - Python
  15. 2005 - JavaScript
  16. 2006 - Ruby
  17. 2007 - PHP

The Present

Currently, I program primarily in Ruby, followed by JavaScript and the occasional PHP script. Ruby is the most productive programming language I’ve used thus far. The combination of power, pragmatism & pleasure in programming is hard to beat. If it also had performance, it would be a truly great language.

I’ve also begun learning Logo as I teach my daughter how to program. Logo is a great introduction to the Lisp family, so I hope to leverage it as I learn Scheme and Common Lisp later this year.

The Future

After completing the Logo course with my daughter, I plan on moving on to Scheme as I go through Structure and Interpretation of Computer Programs which some have called the greatest computer science text ever written.

After Scheme I plan on learning Common Lisp which has the potential to replace Ruby as my primary programming language.

Beyond Logo/Scheme/Common Lisp, the following languages are of interest:

  • Haskell
  • Erlang
  • Lua
  • ML
  • OCaml

If you know of candidates for a future programming language, feel free to add it in a comment.

You may notice that Smalltalk is lacking from the lists above. Despite its prominence in programming language history, I currently don’t feel that Smalltalk is sufficiently better/different than Ruby to warrant an investment in learning it.

After focusing on object oriented for twenty years, I have more of an interest in the functional world of programming languages (and multiple dispatch is cool :) ).

Update: I was just over at Hacker News and saw something I’ve seen many times before. In a nutshell, some guy was stating that Paul Graham’s success with ViaWeb had little to do with his choice of programming language (Lisp) and more to do with him just being a good hacker. In other words, he could’ve written it in any language. I’m so glad Paul responded because his response confirms my thoughts on the matter:

What a weird situation. I keep trying to tell people Lisp is great, and they say, no, no, you guys were just really good programmers. But if I’m such a good programmer, why don’t they believe me?

Paul Graham has written a lot on Lisp and is one of the main factors in me becoming interested in Lisp (along with the fact that Ruby pulled a lot of good ideas from it), but the simple quote above communicates volumes IMO.

Name Guessing in Ruby

Thursday, December 20th, 2007

I came across a web site recently that prompted me to enter two names before I could view the site. So I wondered how difficult it would be to write a Ruby program that could pass the challenge. As you’d expect, it’s trivial in Ruby. If you encounter such a site, please don’t use the code in part two unless it’s permitted by the terms of service of the site in question.

Part One - Obtain a file of names

I found a government site that provided lists of the 1,000 most popular names for each decade, so I wrote a Ruby program to screen scrape the names into a list in order of popularity.

Make the open-uri library available.

require 'open-uri'

Create a simple Struct to contain the url for each decade along with an array for boy names and girl names (the site provides an ordered list for each gender). Then create an array of Decade instances for 80’s, 90’s and 00’s.

Decade = Struct.new(:url, :boy_names, :girl_names)
decades = [
  Decade.new('http://www.ssa.gov/OACT/babynames/decades/names1980s.html', [], []),
  Decade.new('http://www.ssa.gov/OACT/babynames/decades/names1990s.html', [], []),
  Decade.new('http://www.ssa.gov/OACT/babynames/decades/names2000s.html', [], [])
]

Iterate over each decade and screen scrape the list of boy names and girl names.

decades.each do |decade|
  str = open(decade.url).read
  str.scan(/<tr><td align="right">.*?<td width="15%">(w+)</td>.*?<td width="15%">(w+)</td>/m) do
    decade.boy_names << $1
    decade.girl_names << $2
  end
end

Now we have a pair of lists (boys & girls) for each decade with each list in order of popularity - 6 lists in total. We want to form a single list by selecting the most popular name from each of the 6 lists, followed by the second most popular name, etc. The zip function comes to mind, so we’ll first create an array of the 6 lists.

name_lists = decades.inject([]) do |result, decade|
  result << decade.boy_names
  result << decade.girl_names
  result
end

Now we have a list containing 6 lists. Here is where the “everything is an object” aspect of ruby is a bit of a pain. What I want to do is simply zip the 6 lists together, for example:

x = zip(one, two, three, four, five, six)

but I’m forced to pick one of the lists to be the instance for the zip method, for example:

x = one.zip(two, three, four, five, six)

I suppose my dissatisfaction is due in part to my recent research in functional programming.

The line below will do the following (I really like Ruby :) ):

  1. pop one of the lists off of the main list (leaving 5) to be the instance for zip
  2. explode the list of 5 remaining lists into 5 individual arguments via the * operator
  3. zip the 6 lists together
  4. flatten the resulting list of lists produced by zip into one list
  5. remove duplicate entries
  6. write each name to standard output
(name_lists.shift).zip(*name_lists).flatten.uniq.each {|name| puts name }

Run the program as follows to create a file named names.txt which will be used in part two.

ruby scrape_names.rb > names.txt

Part Two - Brute force form submission

Now that we have a list of over 2,000 names, it’s a simple matter of repeatedly trying pairs of names in order of popularity. Here’s the program in its entirety with comments following:

 1  require 'net/http'

 2  names = ARGF.inject([]) {|result, line| result << line.chomp; result } 

 3  Net::HTTP.start('www....com') do |query|
 4    headers = { 'Content-Type' => ‘application/x-www-form-urlencoded’ }
 5    (1…names.length).each do |i|
 6      (0..i).each do |j|
 7        response = query.post(’/guess/’,
 8          “name1=#{names[i]}&name2=#{names[j]}”, headers)
 9        if !response.body.include?(’Failed’)
10          puts “Answer: #{names[i]}, #{names[j]}”
11          exit
12        end
13      end
14    end
15  end

Line 1: makes the HTTP library accessible.

Line 2: reads a list of names from standard input into an array.

Line 3: opens a TCP connection to the specified web server (site withheld for privacy).

Line 4: through trial and error I discovered that contrary to the example in the Pick Axe p. 700, I need to add this header to get the form submission to work.

Lines 5-6: setup the iteration to compare each name (beginning with the second) with each of the previous names up to and including the current one (in case the answer is two identical names).

Lines 7-8: perform an HTTP post with the pair of names.

Lines 9-11: if the retrieved page doesn’t contain a failure string, print the solution to standard output and exit.

Run the program as follows:

ruby guess_names.rb < names.txt

There you have it - a pair of Ruby programs to pass a “guess two names to enter” challenge. The amount of time to find a solution will depend on the uncommonness of the names used. This is an O(n^2) algorithm, so if the names in the solution are near the bottom of the popularity scale, expect a long run time. The name list I produced had 2,697 names, so the worst case scenario is (2697 * 2698) /2 -1 = 3,638,252 requests. If only the first 100 names need to be compared there would be 5,049 requests.

This algorithm is trivial to parallelize - just change line 5 above from (1…names.length) to multiple non-overlapping ranges (one per process), and let her fly.

Ruby has many benefits and is currently my most productive programming language, but I think it particularly shines in this type of ad-hoc, web-enabled task because of the expressiveness of the language and the availability of useful libraries. I highly recommend putting it high on your list of languages to learn if you don’t already use it.

Solving Anagrams in Ruby

Monday, October 22nd, 2007

Someone posted a question on comp.lang.ruby recently asking for help with solving anagrams. The poster originally asked about ways of generating permutations and several people pointed him to the facets library which has some permutation utility functions. As it turns out, I benchmarked the following naive permutation generator as 3 times faster than the facets library code:

def words chars, result='', &b
  if chars.empty?
    yield result
  else
    chars.length.times do |i|
      c = (x = chars.clone).slice!(i)
      words(x, result + c, &b)
    end
  end
end

However, generating all possible combinations of letters in an anagram is a very bad approach which doesn’t take into consideration key knowledge about the problem. Rather than generating all permutations of an anagram, which is infeasible for longer words, we can precompute a hash from our dictionary by using the sorted letters of words as keys. Then to solve an anagram, we simply sort the letters in the anagram and look it up in the hash.

The first program creates the hash and serializes it to disk for future anagram solving:

words = Hash.new([])

File.open("/usr/share/dict/words", "r") do |file|
  while line = file.gets
    word = line.chomp
    words[word.split('').sort!.join('')] += [word]
  end
end

File.open("word_hash", "w") do |file|
  Marshal.dump(words, file)
end

The second program loads the serialized hash from disk to solve anagrams that we type at the console:

words = nil

File.open("word_hash", "r") do |file|
  words = Marshal.load(file)
end

while true
  print "Enter word: "
  anagram = gets.chomp
  sorted_anagram = anagram.split('').sort!.join('')
  p  words[sorted_anagram]
end

This is really fast, but there are probably better methods. If you have one, feel free to add a comment with the code.

Inline C Code in Ruby

Friday, October 5th, 2007

Did you know you can write C code directly within a Ruby program? I learned that at the Ruby Hoedown here in Raleigh and thought I’d share it for those who aren’t aware of it.

First install the rubyinline gem.

sudo gem install rubyinline

Then code :)

require 'rubygems'
require 'inline'

class MyTest
  inline do |builder|
    builder.c "
      long factorial(int max) {
        long result = 1;
        while (max >= 2) {
          result *= max--;
        }
        return result;
      }"
  end
end
t = MyTest.new
puts t.factorial(10)

The first time you run this it will be slower than subsequent runs because the C code will be compiled and cached. Typically you’ll find the generated C code in ~/.ruby_inline

Enjoy,
Brian

Telogis Puzzle

Wednesday, September 19th, 2007

I came across a web site that required job candidates to solve a puzzle to be able to access a job application page. I’m a sucker for puzzles. The original puzzle is at the following site:

http://www.telogis.co.nz/

But in case, they take it down at some point, here is the plain text version nicely formatted:

z = 4254145 * 0x18712495;
b = (z & 1) << 4;
a = b--;
o = [];
c = a - b;
x = b - a;
while (z) {
  x = a & x ? a & b : c + x;
  {
    o[z & b^x] = (x + 6 * a + b / 5 - c).chr;
    z = z / a / a;
  } if (!(z / a & b^x))
}

To apply go to “http://www.telogis.co.nz/” + o + “.html”

I don’t think this will parse correctly in any language, but I decided to solve the puzzle using Ruby since it wasn’t that far from it and Ruby is my main programming language currently. I had a couple false starts due to a subtlety in Ruby compared to other languages.

I’ll come back in a while and post the Ruby solution, but I don’t want to post a spoiler too soon.

8 Queens in Ruby

Friday, September 14th, 2007

I came across a puzzle article that mentioned the 8 Queens problem. It’s been a long time since I encountered it, but I can’t recall if I ever took the time to code it up, so I took a few minutes to code up a couple versions in Ruby. I was impressed with how easy it was in Ruby. If Ruby had the macros and efficiency of Lisp, I’d be pleased.

In a nutshell, the idea is to determine all possible ways to arrange 8 queens on a chessboard so that none are attacking another.

I’m sure my solution is naive since it was pretty much the first approach I thought of, but it cranks out all solutions in a quarter of a second, so it’ll do :)

require 'pp'

def valid? stack
  q2 = stack.length - 1
  (0..stack.length-2).each do |q1|
    return false if stack[q1] == stack[q2] || (q1-q2).abs == (stack[q1]-stack[q2]).abs
  end
end

def queens stack, n
  if n == 8
    pp stack
  else
    (1..8).each do |rank|
      stack.push(rank)
      queens(stack, n+1) if valid?(stack)
      stack.pop
    end
  end
end

queens [], 0

I then became curious about abstracting away the concept of:
1) push something onto a stack
2) do something with the stack
3) pop something off the stack

So, I opened up the Array class and modified push to accept a block.

require 'pp'

class Array
  alias_method :orig_push, :push
  def push obj
    orig_push(obj)
    if block_given?
      yield self
      pop
    end
  end
end

def valid? stack
  q2 = stack.length - 1
  (0..stack.length-2).each do |q1|
    return false if stack[q1] == stack[q2] || (q1-q2).abs == (stack[q1]-stack[q2]).abs
  end
end

def queens stack, n
  if n == 8
    pp stack
  else
    (1..8).each do |rank|
      stack.push(rank) {|s| queens(s, n+1) if valid?(s) }
    end
  end
end

queens [], 0

It makes the code 15% slower, and I don’t like modifying the existing push method in this way, but it does show the convenience of Ruby blocks and how you can extend existing classes. I think a better approach would be to introduce a new function - either standalone as below, or in the Array class.

def push_with_block stack, obj
  stack.push(obj)
  yield stack
  stack.pop
end

Escape from Zurg

Monday, September 10th, 2007

I came across a little programming puzzle on comp.lang.ruby.

The author blogged about it here - nice solution. He refers to the original paper that got things started, but I haven’t had time to read it in depth yet.

I thought I’d try something a little different. I was going for simple and came up with a 3 function solution using just hashes and arrays. It’s not very general except for the handy combinations(array, n) function I wrote, and it certainly doesn’t feel Rubyish, but it was fun.

Something tells me that Lisp can handle this nicely, so I’ll probably write a Lisp version later.

require 'pp'
TOYS = { :buzz => 5, :woody => 10, :rex => 20, :hamm => 25 }

def combinations array, n
  result = []
  if n > 0
    (0 .. array.length - n).each do |i|
      combs = [[]] if (combs = combinations(array[i + 1 .. -1], n - 1)).empty?
      combs.collect {|comb| [array[i]] + comb}.each {|x| result << x}
    end
  end
  return result
end

def generate_states state
  forward = state[:position] == :forward
  args = forward ? [state[:source], 2] : [state[:destination], 1]
  combinations(*args).inject([]) do |states, movers|
    states << {
      :minutes => state[:minutes] - TOYS[movers.max {|a,b| TOYS[a] <=> TOYS[b] }],
      :source => forward ? state[:source] - movers : state[:source] + movers,
      :destination => forward ? state[:destination] + movers : state[:destination] - movers,
      :position => forward ? :backward : :forward,
      :history => state[:history] + [[ state[:position], movers ]] }
    states
  end
end

def play_game state
  if state[:source].empty?
    pp(state[:history]) unless state[:minutes] < 0
  else
    generate_states(state).each {|new_state| play_game new_state }
  end
end

play_game({
  :minutes => 60,
  :source => [ :buzz, :woody, :rex, :hamm ],
  :destination => [],
  :position => :forward,
  :history => [] })

UPDATE: Something didn’t quite feel right about my first solution, so I took a second look at the op’s solution and decided I liked his use of Ruby blocks. They add some flexibility and efficiency in this case. Instead of computing a full array of possible states at each level of recursion (not as bad as precomputing the entire tree, but still not good), the new solution does a depth first search via block yields. I also removed the hardcoded print statement in play_game and yield the solution to the caller’s block to do with as they please.

require 'pp'
TOYS = { :buzz => 5, :woody => 10, :rex => 20, :hamm => 25 }

def combinations array, n
  result = []
  if n > 0
    (0 .. array.length - n).each do |i|
      combs = [[]] if (combs = combinations(array[i + 1 .. -1], n - 1)).empty?
      combs.collect {|comb| [array[i]] + comb}.each {|x| result << x}
    end
  end
  result
end

def execute_move state, forward, movers
  { :minutes => state[:minutes] - TOYS[movers.max {|a,b| TOYS[a] <=> TOYS[b] }],
    :source => forward ? state[:source] - movers : state[:source] + movers,
    :destination => forward ? state[:destination] + movers : state[:destination] - movers,
    :position => forward ? :backward : :forward,
    :history => state[:history] + [[ state[:position], movers ]] }
end

def each_state state
  combinations(*(
    forward = state[:position] == :forward) ?
    [state[:source], 2] :
    [state[:destination], 1]).each {|movers| yield execute_move(state, forward, movers) }
end

def play_game state, &b
  if state[:source].empty?
    yield(state[:history]) unless state[:minutes] < 0
  else
    each_state(state) {|new_state| play_game new_state, &b }
  end
end

play_game({
  :minutes => 60,
  :source => [ :buzz, :woody, :rex, :hamm ],
  :destination => [],
  :position => :forward,
  :history => [] }) {|history| pp history }

Logo, Ruby & JavaScript

Friday, August 31st, 2007

I’ve been teaching my eldest daughter to program in Logo over the summer. Brian Harvey has posted PDF files for a set of excellent books on learning to program in Logo on his web site. The Berkeley version of Logo he’s produced is really excellent. It’s not just your typical turtle graphics language; it has arrays, macros, file processing, graphics, etc.

While perusing his site, I came across a tiny Logo program that demonstrates a little of its power. I was curious what it would look like in Ruby, so I ported it, then I had to see what it looked like in JavaScript.

The formatting is a little messed up due to Wordpress, but each of the three choices functions is 4 lines long.

If anyone wants to add other languages, that would be great!

See the sample page for example output.

Logo

to choices :menu [:sofar []]
  if emptyp :menu [print :sofar stop]
  foreach first :menu [(choices butfirst :menu
      sentence :sofar ?)]
end
choices [[small medium large]
  [vanilla [ultra chocolate] lychee [rum raisin] ginger]
  [cone cup]]

UPDATE 9/2/07: Got an even more concise solution from Brian Harvey:

to choices :menu
   foreach crossmap "sentence :menu "print
end

Ruby

def choices menu, sofar=[]
  if menu.empty?: puts sofar.join(' ')
  else menu[0].each {|item| choices(menu[1..-1],
    sofar + [item]) } end
end
choices [['small', 'medium', 'large'],
  ['vanilla', 'ultra chocolate', 'lychee', 'rum raisin', 'ginger'],
  ['cone', 'cup']]

JavaScript

function choices(menu, sofar) {
  if (emptyp(menu)) print(sofar);
  else foreach(menu[0],
   function (x) {
    choices(menu.slice(1), sofar.concat(x)); });
}
choices([['small', 'medium', 'large'],
  ['vanilla', 'ultra chocolate', 'lychee', 'rum raisin','ginger'],
  ['cone', 'cup']], []);

I had to create a few helpers for the JavaScript version:

function emptyp(a) {
  return a.length === 0;
}
function print(list) {
  foreach(list, function (x) { document.write(x + ' '); });
  document.write('<br />');
}
function foreach(arr, f) {
  for (var idx in arr) { f(arr[idx]); }
}

UPDATE: Use <pre> </pre> tags to allow easier formatting of code. Bummer, I just discovered that Wordpress strips the <pre> tags from normal users :( I’ll go ahead and wrap code with it as they come in, so if your comment looks bad at first, it’ll be cleaned up shortly.

Ruby Hoedown 2007 Videos

Monday, August 20th, 2007

I noticed on Rick DeNatale’s blog that the videos for Ruby Hoedown 2007 are now available.

Ruby Hoedown 2007

Wednesday, August 1st, 2007

I just signed up for the Ruby Hoedown conference. It’s being held here in Raleigh at Red Hat headquarters on August 10 & 11, and the cost is only $100. Speakers include Bruce Tate, Marcel Molina Jr., Ken Auer, Ezra Zygmuntowicz (cool name :) ), Andrea O. K. Wright, Jay Phillips & Jared Richardson.

I also signed up for the charity workshop on testing techniques put on by Marcel Molina, Jr., Bruce Tate, and Chad Fowler - the donation proceeds for that workshop go to the Food Bank of Central & Eastern NC. It will probably be a smaller group with more interaction.

Should be an interesting and fun time - gain some knowledge, make some contacts. Let me know if you’re also planning on attending.

Some links:

Using helpers inside controllers in Ruby on Rails

Friday, July 27th, 2007

Rails provides some nice helper functions (numbers, dates, etc.) that are available to views, but they’re not automatically available to controllers. I found a number of ways to accomplish this on the web, but I wasn’t satisfied with any of them.

The motivation for me to do this was to use the number_to_currency() helper function in a controller, so I’ll use that for the example. This helper is in the ActionView::Helpers::NumberHelper module, which on my Ubuntu 7.04 system is located here:

/usr/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/
action_view/helpers/number_helper.rb

It may be located elsewhere on your system. If you’re running *nix (or OSX), then typing the following command should locate it:

locate number_helper.rb

If you edit number_helper.rb, you’ll notice that NumberHelper is a module and number_to_currency() is an instance method, so we’ll need an instance that has included NumberHelper to be able to call the number_to_currency() method.

One way to do this would be to create a new class that includes the module, and then create an instance of that class:

class MyNumberHelper
include ActionView::Helpers::NumberHelper
end
my_helper = MyNumberHelper.new
formatted_str = my_helper.number_to_currency(n)

If we had an existing object, called obj, another way to accomplish this would be via:

obj.extend(ActionView::Helpers::NumberHelper)

Since I didn’t have an appropriate object to extend the NumberHelper module, I simply created a new one:

Object.new.extend(ActionView::Helpers::NumberHelper)

If I only need to call the helper once, I could accomplish that via:

Object.new.extend(
ActionView::Helpers::NumberHelper).number_to_currency(n)

However, I preferred to create a Proc object and store it for future use:

format_currency = lambda { |n|
Object.new.extend(
ActionView::Helpers::NumberHelper).number_to_currency(n) }

format_currency.call(n)

I deliberately wanted to avoid simply including ActionView::Helpers::NumberHelper in the controller to avoid polluting the namespace and possibly expose additional public methods in the controller.

Ruby User Group June 19

Friday, June 1st, 2007

The Raleigh area Ruby user’s group will be discussing RailsConf on June 19 at 7 pm. at Red Hat Headquarters. Last year when they did this, attendance jumped from ~8 to ~30 and caused them to switch from Panera Bread to Red Hat as the regular meeting place.

It should be an interesting discussion. If you’ve never been to the Ruby user’s group meeting, or if it’s been a while, this one might be worth checking out. They usually have wi-fi setup in the room, so you can multi-task :)

ruby.meetup.com

Feel free to contact me with questions.

Twitter is built with Ruby on Rails

Thursday, April 12th, 2007

I didn’t realize that Twitter was a Ruby on Rails app when I started researching it recently. This post on DHH’s blog informed me of that. The entry references an interview with a Twitter developer about their scaling issues.

By various metrics Twitter is the biggest Rails site on the net right now.

And from DHH’s blog:

Twitter is an amazing success story in terms of rapid user uptake and flattering press. I had a chance to speak with the team a while back about the wild ride they’ve been on. At that time they were fielding spikes of up to 11,000 requests per second across some 16 cores with very little caching thrown into the mix to mitigate. No wonder their site had been feeling slow.

Since I’m currently developing a Ruby on Rails app that has some significant performance requirements, it’s good to see that they’ve been able to handle 11,000 requests per second even if they’re struggling with scaling issues.