<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6888658749995617133</id><updated>2012-02-16T04:32:40.747-08:00</updated><category term='ruby'/><category term='bdd rspec ror'/><title type='text'>Wee will rock you - Software Development Tales</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>7</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-4732943055610119065</id><published>2009-08-12T17:32:00.001-07:00</published><updated>2009-08-12T18:55:32.713-07:00</updated><title type='text'>Rails Dump Format Error Mystery</title><content type='html'>One day your rails app stopped working and the only clue you saw from console log was the 'Dump format error' exception.  It started when users logged in and visit a page and received the dreaded HTTP 500 internal error.  After it happened, they could no longer browse to any page of your rails app, what should you do?&lt;br /&gt;&lt;br /&gt;The first I did was trying to find out what caused this problem, once this exception was thrown, I couldn't reload the page or visit path of the app as it kept showing the 500 error.  I knew it must have something to do with session.  So I closed the web browser and reopened it, it worked but as long as I visited the problematic page, the same problem happened again.&lt;br /&gt;&lt;br /&gt;What does the dump format error mean?  After a quick google, I found out that it was thrown when there was a problem with marshalling/unmarshalling objects.  Who did that?  Why did rails send objects over the wire?  Then I looked at the controller's action and found out this line:&lt;br /&gt;&lt;br /&gt;flash[:object_with_error] = user&lt;br /&gt;&lt;br /&gt;So someone put an object to the flash which was in turn kept in a cookie session data store.  Since the cookie is limited to 4K bytes, storing I suspect that the cookie was full and the data couldn't be fully marshalled.  That caused the dump format error.&lt;br /&gt;&lt;br /&gt;The flash hash usually contains a message to be displayed in a view.  Why did someone put a binary object (in this case, it's an activerecord model) in it?  I found out later that it was because the action took a form, verify the data, and redirect to a different action.  If there were validation errors, it stored the activerecord with errors in the flash so that the redirecting action would be able to fill out the form with errors.&lt;br /&gt;&lt;br /&gt;However, we should avoid storing binary objects in flash (and in cookies) since the object graph can easily exceed the cookie size limit.  Instead, if we really need to pass temporary data between sessions, pass only string values.  In this case, pass only the form data and error messages.&lt;br /&gt;&lt;br /&gt;Problem solved, lesson learned.  Case closed.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-4732943055610119065?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/4732943055610119065/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=4732943055610119065' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/4732943055610119065'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/4732943055610119065'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2009/08/rails-dump-format-error-mystery.html' title='Rails Dump Format Error Mystery'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-7367524753341672526</id><published>2009-07-25T14:50:00.000-07:00</published><updated>2009-07-25T15:43:52.271-07:00</updated><title type='text'>Sort your flickr albums in Ruby with Flickr_fu</title><content type='html'>I have tons of photos in &lt;a href="http://www.flickr.com/"&gt;flickr&lt;/a&gt; organized by photo sets.  Each photo set name has a date prefix like '20090725 Chicago downtown'.  I use the prefix to sort album folders in my local drive.  However when I upload them to flickr, if I don't upload them in the same order, I will have to use Flickr's &lt;a href="http://www.flickr.com/photos/organize/"&gt;Organize&lt;/a&gt; to manually drag and drop ones to the right place.  It is tedious and there is no quick and easy way to automate it.&lt;br /&gt;&lt;br /&gt;I know that flickr provides APIs that allow developers to manage photos programatially in pratically any modern language.  Since I am a fan of Ruby, I chose a ruby libray, &lt;a href="http://github.com/commonthread/flickr_fu/tree/master"&gt;flickr_fu&lt;/a&gt; from &lt;a href="http://blog.commonthread.com/"&gt;commontread&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;So I take an hour to set up and write a ruby class to re-order my 1000+ photosets.  The class name is FlickrPhotoSetSorter.  Here is the step that I did and you can follow, assuming you have ruby 1.8+ installed.&lt;br /&gt;&lt;br /&gt;1. Install flickr_fu&lt;br /&gt;&lt;pre&gt;sudo gem install flickr-fu&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;You may have to install a required gem; xml-magic separately.&lt;br /&gt;&lt;br /&gt;2. Create flickr.yml to store my flickr API key and secret key.  Replace "your key" and "your secret" with the yours.  You may obtain them from &lt;a href="http://www.flickr.com/services/api/keys/"&gt;Flickr API keys&lt;/a&gt;.  The token_cache.yml is a file flickr_fu uses to store your session token (flickr calls it 'frob').&lt;br /&gt;&lt;pre&gt;## YAML Template.&lt;br /&gt;--- !map:Hash&lt;br /&gt;key: "your key"&lt;br /&gt;secret: "your secret"&lt;br /&gt;token_cache: "token_cache.yml"&lt;/pre&gt;3. Authorize your program to read/write your albums.  I defined a method, authorize, in my FlickrPhotoSetSorter class.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;require 'flickr_fu'&lt;br /&gt;&lt;br /&gt;class FlickrPhotoSetSorter&lt;br /&gt;  def initialize&lt;br /&gt;    @flickr = Flickr.new('flickr.yml')&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def authorize&lt;br /&gt;    puts "visit the following url, then click &lt;enter&gt; once you have authorized:"&lt;br /&gt;    # request write permissions&lt;br /&gt;    puts @flickr.auth.url(:write)&lt;br /&gt;    gets&lt;br /&gt;    flickr.auth.cache_token&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;FlickrPhotoSetSorter.new.authorize&lt;br /&gt;&lt;/pre&gt;The method generates and displays a URL to flickr.com that you will have to visit in order to ensure that you have rights to your account.  Here is an example of the result.  I replaced all ids with a dummy 12345.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;visit the following url, then click &lt;enter&gt; once you have authorize&lt;br /&gt;http://flickr.com/services/auth/?frob=12345&amp;amp;auth_token=12345&amp;amp;api_key=12345&amp;amp;perms=write&amp;amp;api_sig=12345&lt;br /&gt;&lt;/pre&gt;4. Once I authorized the application, I can start loading a list of my photosets using flickr_fu's Photosets class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;  def photosets_list&lt;br /&gt;    Flickr::Photosets.new(@flickr).get_list&lt;br /&gt;  end&lt;/pre&gt;5. Since I have a large collection of my photosets, I don't want to load them from flickr.com every time I run the script.  So I chose to store the result into a file that I can load later.  I created a file, list.txt and store each photoset with id, number of photos, title and description separated by a pipe symbol '|'&lt;br /&gt;&lt;pre&gt;  def store_photoset_list(file_name = 'list.txt')&lt;br /&gt;    File.open(file_name, "w") do |file|&lt;br /&gt;      photosets_list.map do |photoset|&lt;br /&gt;        file.puts("#{photoset.id}|#{photoset.num_photos}|#{photoset.title}|#{photoset.description}")&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;FlickrPhotoSetSorter.new.store_photoset_list&lt;/pre&gt;6. To load it back, firstly I created a method to read a line and returns a hash that contain the information from a photoset.&lt;br /&gt;&lt;pre&gt;  def photoset_from(line)&lt;br /&gt;    id, num_photos, title, description = line.split('|')&lt;br /&gt;    return nil unless id.to_i &gt; 0&lt;br /&gt;    { :id =&gt; id,&lt;br /&gt;      :num_photos =&gt; num_photos,&lt;br /&gt;      :title =&gt; title,&lt;br /&gt;      :description =&gt; description }&lt;br /&gt;  end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Then, I defined a method to load the file and build an photoset array.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;  def load_photoset_list(file_name = 'list.txt')&lt;br /&gt;    return @photosets_list if @photosets_list&lt;br /&gt;    @photosets_list = []&lt;br /&gt;    lines = IO.readlines(file_name)&lt;br /&gt;    lines.each do |line|&lt;br /&gt;      @photosets_list &lt;&lt; photoset_from(line)&lt;br /&gt;    end&lt;br /&gt;    @photosets_list.compact&lt;br /&gt;  end&lt;/pre&gt;7. Since flickr_fu does not have a method to sort or update the order of photosets, I have to do it by myself.  It is super easy since I already have everything I need.  Flickr has an API to order photo sets, &lt;a href="http://www.flickr.com/services/api/flickr.photosets.orderSets.html"&gt;flickr.photosets.orderSets&lt;/a&gt; and it requires a list of photoset ids separated by commas.&lt;br /&gt;&lt;br /&gt;So I sort the photoset by title descending and collect ids and join them with ','.  At the end, I use flickr_fu's send_request and pass the API name with the list of photoset ids using HTTP post.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;  def order_photosets_by_title&lt;br /&gt;    ordered_list = load_photoset_list.sort { |a,b| (b[:title] || "") &lt;=&gt; (a[:title] || "") }&lt;br /&gt;    ordered_ids = ordered_list.map { |set| set[:id] }.join(',')&lt;br /&gt;    @flickr.send_request('flickr.photosets.orderSets', { :photoset_ids =&gt; ordered_ids }, :post)&lt;br /&gt;  end&lt;/pre&gt;8. To run the script, just use:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;FlickrPhotoSetSorter.new.order_photosets_by_title&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That's it.  Now my photoset list are sorted by title descending order.  I can upload older photosets, rerun the script and have them sort again and never worry that my photosets will be out of order again.&lt;br /&gt;&lt;br /&gt;Here is the entire source code of the FlickrPhotoSetSorter class.&lt;br /&gt;&lt;pre&gt;require 'flickr_fu'&lt;br /&gt;&lt;br /&gt;class FlickrPhotoSetSorter&lt;br /&gt;  def initialize&lt;br /&gt;    @flickr = Flickr.new('flickr.yml')&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def authorize&lt;br /&gt;    puts "visit the following url, then click &lt;enter&gt; once you have authorized:"&lt;br /&gt;    # request write permissions&lt;br /&gt;    puts @flickr.auth.url(:write)&lt;br /&gt;    gets&lt;br /&gt;    flickr.auth.cache_token&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def photosets_list&lt;br /&gt;    Flickr::Photosets.new(@flickr).get_list&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def store_photoset_list(file_name = 'list.txt')&lt;br /&gt;    File.open(file_name, "w") do |file|&lt;br /&gt;      photosets_list.map do |photoset|&lt;br /&gt;        file.puts("#{photoset.id}|#{photoset.num_photos}|#{photoset.title}|#{photoset.description}")&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def load_photoset_list(file_name = 'list.txt')&lt;br /&gt;    return @photosets_list if @photosets_list&lt;br /&gt;    @photosets_list = []&lt;br /&gt;    lines = IO.readlines(file_name)&lt;br /&gt;    lines.each do |line|&lt;br /&gt;      @photosets_list &lt;&lt; photoset_from(line)&lt;br /&gt;    end&lt;br /&gt;    @photosets_list.compact&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def photoset_from(line)&lt;br /&gt;    id, num_photos, title, description = line.split('|')&lt;br /&gt;    return nil unless id.to_i &gt; 0&lt;br /&gt;    { :id =&gt; id,&lt;br /&gt;      :num_photos =&gt; num_photos,&lt;br /&gt;      :title =&gt; title,&lt;br /&gt;      :description =&gt; description }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def order_photosets_by_title&lt;br /&gt;    ordered_list = load_photoset_list.sort { |a,b| (b[:title] || "") &lt;=&gt; (a[:title] || "") }&lt;br /&gt;    ordered_ids = ordered_list.map { |set| set[:id] }.join(',')&lt;br /&gt;    @flickr.send_request('flickr.photosets.orderSets', { :photoset_ids =&gt; ordered_ids }, :post)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Feel free to use the code for you needs.  If you want to reorder with different criteria, update the sort block in the order_photosets_by_title method.  Rename the method as appropriate.&lt;br /&gt;&lt;br /&gt;Enjoy.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-7367524753341672526?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/7367524753341672526/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=7367524753341672526' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/7367524753341672526'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/7367524753341672526'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2009/07/sort-your-flickr-albums-in-ruby-with.html' title='Sort your flickr albums in Ruby with Flickr_fu'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-323952695355304971</id><published>2009-03-14T21:35:00.000-07:00</published><updated>2009-03-14T22:38:29.367-07:00</updated><title type='text'>Small quiz solutions in 12 languages</title><content type='html'>Last week I posted a short programming quiz in my Thai development community at narisa.com and asked members to come up with solutions in many languages as possible.  We finally got 12 solutions implemented in C, C#, Clojure, Erlang, Groovy, Haskell, Java, PHP, Python, Ruby, Scala, Visual Basic with LINQ.  Some languages have more than one implementations.&lt;br /&gt;&lt;br /&gt;The quiz is about parsing and sorting an input text file.  There are records; one per line.  Each record has many fields delimited by a pipe symbol '|'.  The first field is a record number.  We want to sort all the records by this number and display the sorted result one record per line.  Each line will display the record number followed by sorted fields. (The original problem didn't have number sort and first column exclusion constraints)&lt;br /&gt;&lt;br /&gt;For example, an input.txt file:&lt;br /&gt;&lt;blockquote&gt;13|hello|world|bangkok&lt;br /&gt;4|1monkey|ant|dog|cow|cat&lt;br /&gt;2|pink|yellow|red|magenta&lt;br /&gt;1|earth|sun|jupiter|pluto&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;The expected result:&lt;br /&gt;&lt;blockquote&gt;1 earth jupiter pluto sun&lt;br /&gt;2 magenta pink red yellow&lt;br /&gt;4 1monkey ant cat cow dog &lt;br /&gt;13 bangkok hello world&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;Notice that the record number 13 is after record number 4. So we need to compare the number by value, not by string literal.  Each record has to exclude the field number and sort the rest alphabetically.&lt;br /&gt;&lt;br /&gt;Here are solutions.  Your truly provided 2 solutions in Ruby and Scala.  You will see that Thai development community is quite vibrant from a variety of language choices.  Look like Groovy is among the most popular one.  You will see that scripting languages are good for this kind of problem in terms of compactness and declarative style.  Read the original post in Thai &lt;a href="http://www.narisa.com/forums/index.php?showtopic=27192&amp;st=0"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;C (gcc)&lt;/span&gt; by iWat&lt;br /&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;#include &amp;lt;string.h&amp;gt;&lt;br /&gt;&lt;br /&gt;struct record&lt;br /&gt;{&lt;br /&gt;int number;&lt;br /&gt;&lt;br /&gt;int num_fields;&lt;br /&gt;char **fields;&lt;br /&gt;&lt;br /&gt;char *buffer;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;static int record_number_comparator(struct record *first, struct record *second)&lt;br /&gt;{&lt;br /&gt;return first-&amp;gt;number - second-&amp;gt;number;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;static void bubble_sort(void **ar_p_struct, int count, int (*comparator)(void *, void *))&lt;br /&gt;{&lt;br /&gt;int i;&lt;br /&gt;int j;&lt;br /&gt;&lt;br /&gt;for (i = 0; i &amp;lt; count - 1; ++i)&lt;br /&gt;{&lt;br /&gt;for (j = 0; j &amp;lt; count - 1 - i; ++j)&lt;br /&gt;{&lt;br /&gt;if (comparator(ar_p_struct[j+1], ar_p_struct[j]) &amp;lt; 0) {&lt;br /&gt;void *p_tmp;&lt;br /&gt;&lt;br /&gt;p_tmp = ar_p_struct[j];&lt;br /&gt;ar_p_struct[j] = ar_p_struct[j + 1];&lt;br /&gt;ar_p_struct[j + 1] = p_tmp;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;static void print_record(struct record *my_record)&lt;br /&gt;{&lt;br /&gt;int i;&lt;br /&gt;&lt;br /&gt;for (i = 0; i &amp;lt; my_record-&amp;gt;num_fields; ++i)&lt;br /&gt;{&lt;br /&gt;printf(&amp;quot;%s &amp;quot;, my_record-&amp;gt;fields[i]);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;printf(&amp;quot;\n&amp;quot;);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;static void parse_records(FILE *fp, struct record ***p_ar_p_records, int *p_num_records)&lt;br /&gt;{&lt;br /&gt;char buffer[256];&lt;br /&gt;&lt;br /&gt;*p_num_records = 0;&lt;br /&gt;*p_ar_p_records = NULL;&lt;br /&gt;&lt;br /&gt;while (fgets(buffer, 256, fp) != NULL)&lt;br /&gt;{&lt;br /&gt;struct record *current_record = malloc(sizeof(struct record));&lt;br /&gt;&lt;br /&gt;current_record-&amp;gt;num_fields = 0;&lt;br /&gt;current_record-&amp;gt;fields = malloc(10 * sizeof(char *));&lt;br /&gt;current_record-&amp;gt;buffer = strdup(buffer);&lt;br /&gt;&lt;br /&gt;char *start = current_record-&amp;gt;buffer;&lt;br /&gt;char *pointer = start;&lt;br /&gt;&lt;br /&gt;while(1)&lt;br /&gt;{&lt;br /&gt;if (*pointer == '|' || *pointer == '\0')&lt;br /&gt;{&lt;br /&gt;current_record-&amp;gt;fields[current_record-&amp;gt;num_fields] = start;&lt;br /&gt;&lt;br /&gt;start = pointer + 1;&lt;br /&gt;&lt;br /&gt;if (current_record-&amp;gt;num_fields == 0)&lt;br /&gt;current_record-&amp;gt;number = atoi(current_record-&amp;gt;fields[0]);&lt;br /&gt;&lt;br /&gt;++current_record-&amp;gt;num_fields;&lt;br /&gt;&lt;br /&gt;if (*pointer == '\0')&lt;br /&gt;{&lt;br /&gt;if (*(pointer - 1) == '\n')&lt;br /&gt;*(pointer - 1) = '\0';&lt;br /&gt;break;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;*pointer = '\0';&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;++pointer;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;++(*p_num_records);&lt;br /&gt;*p_ar_p_records = (struct record **) realloc(*p_ar_p_records, sizeof(struct record *) * (*p_num_records));&lt;br /&gt;(*p_ar_p_records)[(*p_num_records) - 1] = current_record;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char **argv)&lt;br /&gt;{&lt;br /&gt;int i;&lt;br /&gt;int num_records;&lt;br /&gt;struct record **ar_p_records;&lt;br /&gt;&lt;br /&gt;FILE *fp;&lt;br /&gt;&lt;br /&gt;if (argc != 2)&lt;br /&gt;{&lt;br /&gt;printf(&amp;quot;Usage: %s &amp;lt;input file&amp;gt;\n&amp;quot;, argv[0]);&lt;br /&gt;return 1;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;fp = fopen(argv[1], &amp;quot;r&amp;quot;);&lt;br /&gt;&lt;br /&gt;if (fp == NULL)&lt;br /&gt;{&lt;br /&gt;printf(&amp;quot;error reading file: %s\n&amp;quot;, argv[1]);&lt;br /&gt;return 2;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;parse_records(fp, &amp;amp;ar_p_records, &amp;amp;num_records);&lt;br /&gt;&lt;br /&gt;printf(&amp;quot;===== parse result\n&amp;quot;);&lt;br /&gt;&lt;br /&gt;for (i = 0; i &amp;lt; num_records; ++i)&lt;br /&gt;{&lt;br /&gt;print_record(ar_p_records[i]);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;bubble_sort((void **) ar_p_records, num_records, (int(*)(void *, void *)) record_number_comparator);&lt;br /&gt;&lt;br /&gt;printf(&amp;quot;\n===== sort result\n&amp;quot;);&lt;br /&gt;&lt;br /&gt;for (i = 0; i &amp;lt; num_records; ++i)&lt;br /&gt;{&lt;br /&gt;bubble_sort(&lt;br /&gt;(void **) (ar_p_records[i]-&amp;gt;fields + 1),&lt;br /&gt;ar_p_records[i]-&amp;gt;num_fields - 1,&lt;br /&gt;(int(*)(void *, void *)) strcmp);&lt;br /&gt;print_record(ar_p_records[i]);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;fclose(fp);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;C# with LINQ&lt;/span&gt; by bleak&lt;br /&gt;&lt;code&gt;using System;&lt;br /&gt;using System.Linq;&lt;br /&gt;&lt;br /&gt;class FunCode&lt;br /&gt;{&lt;br /&gt;    static void Main(string[] args)&lt;br /&gt;    {&lt;br /&gt;        string[] records = System.IO.File.ReadAllLines("input.txt");&lt;br /&gt;        var rs = from r in records&lt;br /&gt;                 let fields = r.Split('|')&lt;br /&gt;                 orderby int.Parse(fields[0])&lt;br /&gt;                 select string.Concat(fields[0], " ", string.Join(" ", fields.Skip(1).OrderBy(x =&gt; x).ToArray()));&lt;br /&gt;        foreach (var r in rs)&lt;br /&gt;            Console.WriteLine(r);&lt;br /&gt;    }&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Clojure&lt;/span&gt; by pphetra&lt;br /&gt;&lt;code&gt;(defn outer-sort [xs]&lt;br /&gt;   (sort-by #(first %) xs))&lt;br /&gt;&lt;br /&gt;(defn inner-sort [xs]&lt;br /&gt;   (let [fst (first xs)&lt;br /&gt;         rst (sort (rest xs))]&lt;br /&gt;     (cons fst rst)))&lt;br /&gt;&lt;br /&gt;(defn solve [xs]&lt;br /&gt;   (outer-sort (map inner-sort xs)))&lt;br /&gt;&lt;br /&gt;(defn read-file [file-name]&lt;br /&gt;  (let [raw-lines (seq (.split (slurp file-name) "\n"))&lt;br /&gt;        lines (map #(seq (.split % "\\|")) raw-lines)]&lt;br /&gt;    lines))&lt;br /&gt;&lt;br /&gt;(defn pretty-print [xs]&lt;br /&gt;  (doseq [line xs]&lt;br /&gt;    (do (doseq [word line]&lt;br /&gt;          (print word ""))&lt;br /&gt;        (print "\n"))))&lt;br /&gt;&lt;br /&gt;;; ตัวอย่างการใช้&lt;br /&gt;(pretty-print (solve (read-file "input.txt")))&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Coldfusion&lt;/span&gt; by iporsut&lt;br /&gt;&lt;code&gt;&amp;lt;cfset recordset = QueryNew(&amp;quot;id, list&amp;quot; , &amp;quot;Integer, VarChar&amp;quot;)&amp;gt;&lt;br /&gt;&amp;lt;cfset count = 1 /&amp;gt;&lt;br /&gt;&amp;lt;cfloop file=&amp;quot;#Expandpath('/')#input.txt&amp;quot; index=&amp;quot;line&amp;quot;&amp;gt;&lt;br /&gt;&amp;lt;cfscript&amp;gt;&lt;br /&gt;    line = listChangeDelims(line,&amp;quot;,&amp;quot;,&amp;quot;|&amp;quot;);&lt;br /&gt;      id = listfirst(line);&lt;br /&gt;    list = listsort(listrest(line) , &amp;quot;text&amp;quot;, &amp;quot;asc&amp;quot;);&lt;br /&gt;    list = listChangeDelims(list,&amp;quot; &amp;quot;,&amp;quot;,&amp;quot;);&lt;br /&gt;&lt;br /&gt;    QueryAddRow(recordset,1);&lt;br /&gt;    QuerySetCell(recordset,&amp;quot;id&amp;quot;,id,count);&lt;br /&gt;    QuerySetCell(recordset,&amp;quot;list&amp;quot;,list,count);&lt;br /&gt;&lt;br /&gt;    count++;&lt;br /&gt;&amp;lt;/cfscript&amp;gt;&lt;br /&gt;&amp;lt;/cfloop&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;cfquery dbtype=&amp;quot;query&amp;quot; name=&amp;quot;qSortedRecord&amp;quot;&amp;gt;&lt;br /&gt;    select id,list&lt;br /&gt;    from recordset&lt;br /&gt;    order by id asc&lt;br /&gt;&amp;lt;/cfquery&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;cfoutput query=&amp;quot;qSortedRecord&amp;quot;&amp;gt;&lt;br /&gt;    #qSortedRecord.id# #qSortedRecord.list# &amp;lt;br /&amp;gt;&lt;br /&gt;&amp;lt;/cfoutput&amp;gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Erlang&lt;/span&gt; by pphetra&lt;br /&gt;&lt;code&gt;-module(s1).&lt;br /&gt;-export([solve/1]).&lt;br /&gt;&lt;br /&gt;-import(lists, [sort/2,sort/1]).&lt;br /&gt;-import(string, [tokens/2, to_integer/1]).&lt;br /&gt;&lt;br /&gt;% เขาว่า read แบบ binary จะ performance ดีกว่า&lt;br /&gt;readfile(FileName) -&gt;&lt;br /&gt;    {ok, Binary} = file:read_file(FileName),&lt;br /&gt;    tokens(erlang:binary_to_list(Binary), "\n").&lt;br /&gt;&lt;br /&gt;% แต่ละ line ที่ได้มาให้ split tokens ด้วย    &lt;br /&gt;parse(FileName) -&gt;&lt;br /&gt;    [ tokens(Line, "|") || Line &lt;- readfile(FileName)].&lt;br /&gt;&lt;br /&gt;% sort โดยใช้ Head Element และแปลงเป็น integer ก่อน sort    &lt;br /&gt;outer_sort(List) -&gt;&lt;br /&gt;    sort(fun ([H1|_], [H2|_]) -&gt; to_integer(H1) =&lt; to_integer(H2) end, List).&lt;br /&gt;    &lt;br /&gt;solve(FileName) -&gt;&lt;br /&gt;    outer_sort([ [H | sort(T)] || [H|T] &lt;- parse(FileName)]).&lt;br /&gt;&lt;br /&gt;1&gt; c(s1).                &lt;br /&gt;{ok,s1}&lt;br /&gt;2&gt; s1:solve('input.txt').&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Groovy&lt;/span&gt; #1 by cblue&lt;br /&gt;&lt;code&gt;def result=[:]&lt;br /&gt;new File('input.txt').eachLine {&lt;br /&gt;    def line = it.tokenize('|')&lt;br /&gt;    result[line[0] as int] = line[1..-1].sort()&lt;br /&gt;}&lt;br /&gt;result.sort{ e1, e2 -&gt; e1.key - e2.key }.each { k, v -&gt;&lt;br /&gt;    println "$k ${v.join(' ')}"&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Groovy&lt;/span&gt; #2 by cblue&lt;br /&gt;&lt;code&gt;def result = new File('input.txt').readLines().collect {&lt;br /&gt;  def line = it.tokenize('|')&lt;br /&gt;  [line.head() as int] + line.tail().sort()  &lt;br /&gt;}&lt;br /&gt;result.sort { o1, o2 -&gt; o1[0] &lt;=&gt; o2[0] }.each {&lt;br /&gt;  println it.join(' ')&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Groovy&lt;/span&gt; #3 by xcaleber&lt;br /&gt;&lt;code&gt;&lt;br /&gt;new File("input.txt").readLines()*.tokenize("|").sort{one, another -&gt; one[0] &lt;=&gt; another[0]}.each{ println "${it[0]} ${it[1..-1].sort().join(' ')}" }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Haskell&lt;/span&gt; #1 by iporsut&lt;br /&gt;&lt;code&gt;import List&lt;br /&gt;&lt;br /&gt;compareFirst::[[Char]]-&gt;[[Char]]-&gt;Ordering&lt;br /&gt;compareFirst a b | (read (head a)::Int) &gt;= (read (head b)::Int) = GT&lt;br /&gt;                 | otherwise = LT&lt;br /&gt;&lt;br /&gt;transformPipeToSpace::[Char]-&gt;[Char]&lt;br /&gt;transformPipeToSpace a = map transform a&lt;br /&gt;                        where&lt;br /&gt;                            transform b | b == '|' = ' '&lt;br /&gt;                                        | otherwise = b&lt;br /&gt;inputToWords::[Char]-&gt;[[[Char]]]&lt;br /&gt;inputToWords input = map words (map transformPipeToSpace (lines input))&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;wordsToOutput::[[[Char]]]-&gt;[Char]&lt;br /&gt;wordsToOutput word = foldl (++) "" (map unwordsNewline word)&lt;br /&gt;                    where&lt;br /&gt;                        unwordsNewline w = (unwords w)++['\n']&lt;br /&gt;&lt;br /&gt;sortRecords::[Char]-&gt;[[[Char]]]&lt;br /&gt;sortRecords input = map sortWords (sortBy compareFirst (inputToWords input))&lt;br /&gt;                    where&lt;br /&gt;                        sortWords (x:xs) = x:(sort xs)&lt;br /&gt;main = do&lt;br /&gt;    input &lt;- readFile "input.txt"&lt;br /&gt;    putStrLn (wordsToOutput (sortRecords input))&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Haskell&lt;/span&gt; #2 by pphetra&lt;br /&gt;&lt;code&gt;import List&lt;br /&gt;&lt;br /&gt;split delim s&lt;br /&gt;    | [] &lt;- rest = [token]&lt;br /&gt;    | otherwise = token : split (delim) (tail rest)&lt;br /&gt;    where (token,rest) = span (/= delim) s&lt;br /&gt;&lt;br /&gt;compareFirst a b | (read (head a)::Int) &gt;= (read (head b)::Int) = GT&lt;br /&gt;                 | otherwise = LT&lt;br /&gt;                    &lt;br /&gt;splitAndSort s = head xs : sort (tail xs)&lt;br /&gt;    where xs = split '|' s&lt;br /&gt;&lt;br /&gt;main = do&lt;br /&gt;    input &lt;- readFile "s1.txt"&lt;br /&gt;    putStrLn $ (unlines . map unwords . sortBy compareFirst . map splitAndSort . lines) input&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Java&lt;/span&gt; #1 by comx&lt;br /&gt;&lt;code&gt;package javaapplication1;&lt;br /&gt;&lt;br /&gt;import java.io.*;&lt;br /&gt;import java.util.*;&lt;br /&gt;&lt;br /&gt;public class Main {&lt;br /&gt;    public static void main(String[] args) throws Exception {&lt;br /&gt;        Reader r = new FileReader("c:/input.txt");&lt;br /&gt;        BufferedReader br = new BufferedReader(r);&lt;br /&gt;        SortedSet&lt;LineItem&gt; lineItemHolder = new TreeSet&lt;LineItem&gt;();&lt;br /&gt;        while (true) {&lt;br /&gt;            String line = br.readLine();&lt;br /&gt;            if (line == null) {&lt;br /&gt;                break;&lt;br /&gt;            }&lt;br /&gt;            lineItemHolder.add(new LineItem(line));&lt;br /&gt;        }&lt;br /&gt;        print(lineItemHolder);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void print(Collection items) {&lt;br /&gt;        for (Object object : items) {&lt;br /&gt;            System.out.println(object);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Java&lt;/span&gt; #2 by panther&lt;br /&gt;&lt;code&gt;import java.io.*;&lt;br /&gt;import java.util.*;&lt;br /&gt;&lt;br /&gt;class FooSort&lt;br /&gt;{&lt;br /&gt;    public static void main(String[] args)throws Exception&lt;br /&gt;    {    &lt;br /&gt;        BufferedReader br = new BufferedReader( new FileReader(&amp;quot;c:/input.txt&amp;quot;) );&lt;br /&gt;        Map&amp;lt;Integer, List&amp;lt;String&amp;gt;&amp;gt; tm = new TreeMap&amp;lt;Integer, List&amp;lt;String&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;        while( true ){&lt;br /&gt;                &lt;br /&gt;            String line = br.readLine();&lt;br /&gt;                &lt;br /&gt;            if( line == null ){&lt;br /&gt;                break;&lt;br /&gt;            }&lt;br /&gt;                &lt;br /&gt;            String[] record = line.split(&amp;quot;[|]&amp;quot;);&lt;br /&gt;            List&amp;lt;String&amp;gt; list = Arrays.asList( record );&lt;br /&gt;            &lt;br /&gt;            Collections.sort( list );&lt;br /&gt;                &lt;br /&gt;            tm.put( Integer.parseInt( list.get( 0 ) ) , list );        &lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        Iterator&amp;lt;Map.Entry&amp;lt;Integer, List&amp;lt;String&amp;gt;&amp;gt;&amp;gt; it =&lt;br /&gt;                                 ((Set&amp;lt;Map.Entry&amp;lt;Integer, List&amp;lt;String&amp;gt;&amp;gt;&amp;gt;)tm.entrySet()).iterator();&lt;br /&gt;            &lt;br /&gt;        while( it.hasNext() ){&lt;br /&gt;            renderlist( it.next().getValue() );&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    public static void renderlist( List&amp;lt;String&amp;gt; list ){&lt;br /&gt;        &lt;br /&gt;        Iterator&amp;lt;String&amp;gt; it = list.iterator();&lt;br /&gt;        &lt;br /&gt;        while( it.hasNext() ){&lt;br /&gt;            System.out.print( it.next() + &amp;quot; &amp;quot; );&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        System.out.println();&lt;br /&gt;    }&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;PHP&lt;/span&gt; by Rux&lt;br /&gt;&lt;code&gt;&amp;lt;?php&lt;br /&gt;    $lines = file('input.txt');&lt;br /&gt;&lt;br /&gt;    foreach($lines as $line){&lt;br /&gt;        $key = substr($line, 0, strpos($line, '|'));&lt;br /&gt;        $ds[$key] = explode('|', $line);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ksort($ds);&lt;br /&gt;&lt;br /&gt;    foreach($ds as $rw){&lt;br /&gt;        sort($rw);&lt;br /&gt;        echo implode(&amp;quot;&amp;amp;nbsp;&amp;quot;, $rw);&lt;br /&gt;        echo &amp;quot;&amp;lt;br /&amp;gt;&amp;quot;;&lt;br /&gt;    }    &lt;br /&gt;?&amp;gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Ruby&lt;/span&gt; by your truely&lt;br /&gt;&lt;code&gt;lines = IO.readlines('input.txt').map do |line|&lt;br /&gt;  items = line.chomp.split('|')&lt;br /&gt;  [items.shift] + items.sort&lt;br /&gt;end&lt;br /&gt;lines.sort { |one, another| one[0].to_i &lt;=&gt; another[0].to_i }.each do |line|&lt;br /&gt;  puts line.join(' ')&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Ruby with UNIX commands&lt;/span&gt; by pphetra&lt;br /&gt;&lt;code&gt;ruby -F'\|' -nlae 'puts $F[1..-1].sort().unshift($F[0]).join(" ")' input.txt | sort -nk 1&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Scala&lt;/span&gt; by your truly&lt;br /&gt;&lt;code&gt;import scala.io.Source&lt;br /&gt;import scala.util.Sorting&lt;br /&gt;&lt;br /&gt;def show_sort(fileName: String) = {&lt;br /&gt;  def sort_record(line: String) = {&lt;br /&gt;    val fields = List.fromString(line.replace("\n", ""), '|')&lt;br /&gt;    fields.head :: fields.tail.sort((a,b) =&gt; (a compareTo b) &lt; 0)&lt;br /&gt;  }&lt;br /&gt;  val tuples = Source.fromFile(fileName).getLines.map(sort_record).collect&lt;br /&gt;  val sort_tuples = Sorting.stableSort(tuples, (a:List[String], b:List[String]) =&gt; a.head.toInt &lt; b.head.toInt)&lt;br /&gt;  sort_tuples.map(tuple =&gt; println(tuple.mkString("", " ", "")))&lt;br /&gt;}&lt;br /&gt;show_sort("input.txt")&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;VisualBasic.NET with LINQ&lt;/span&gt; by tuckclub&lt;br /&gt;&lt;code&gt;Module Module1&lt;br /&gt;&lt;br /&gt;    Sub Main()&lt;br /&gt;        Dim records = System.IO.File.ReadAllLines("input.txt")&lt;br /&gt;        Dim rs = From r In records _&lt;br /&gt;                 Let ia = r.Split("|") _&lt;br /&gt;                 Let ca = (From c In ia.Skip(1) Order By c) _&lt;br /&gt;                 Order By ia(0) _&lt;br /&gt;                 Select ia.Take(1).Union(ca).ToArray&lt;br /&gt;        For Each r In rs&lt;br /&gt;            Console.WriteLine(String.Join(" ", r))&lt;br /&gt;        Next&lt;br /&gt;        Console.ReadKey()&lt;br /&gt;    End Sub&lt;br /&gt;&lt;br /&gt;End Module&lt;/code&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-323952695355304971?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/323952695355304971/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=323952695355304971' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/323952695355304971'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/323952695355304971'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2009/03/small-quiz-solutions-in-12-languages.html' title='Small quiz solutions in 12 languages'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-3316981238765646636</id><published>2009-02-20T16:44:00.000-08:00</published><updated>2009-02-20T16:57:10.382-08:00</updated><title type='text'>irb with autocompletion support</title><content type='html'>Interactive ruby shell (irb) is a handy tool for exploratory programming in ruby.  One of lesser known features in irb is tab autocompletion support.  Say, you want to know instance methods of a particular object, you can type the object followed by a dot and then hit a tab.  irb will display all instance methods on that object.&lt;br /&gt;&lt;br /&gt;Below is an example of methods for a number 1.  After you type 1., hit a tab key.  (Oh yeah, 1 is an object in ruby)&lt;br /&gt;&lt;br /&gt;&lt;code&gt;$ irb -r irb/completion&lt;br /&gt;irb(main):001:0&gt; 1.&lt;br /&gt;                              1.eql?                        1.instance_variable_get       1.prec_f                      1.taint&lt;br /&gt;1.__id__                      1.equal?                      1.instance_variable_set       1.prec_i                      1.tainted?&lt;br /&gt;1.__send__                    1.even?                       1.instance_variables          1.pred                        1.tap&lt;br /&gt;1.abs                         1.extend                      1.integer?                    1.private_methods             1.times&lt;br /&gt;1.between?                    1.fdiv                        1.is_a?                       1.protected_methods           1.to_a&lt;br /&gt;1.ceil                        1.floor                       1.kind_of?                    1.public_methods              1.to_enum&lt;br /&gt;1.chr                         1.freeze                      1.method                      1.quo                         1.to_f&lt;br /&gt;1.class                       1.frozen?                     1.methods                     1.remainder                   1.to_i&lt;br /&gt;1.clone                       1.hash                        1.modulo                      1.respond_to?                 1.to_int&lt;br /&gt;1.coerce                      1.id                          1.next                        1.round                       1.to_s&lt;br /&gt;1.display                     1.id2name                     1.nil?                        1.send                        1.to_sym&lt;br /&gt;1.div                         1.inspect                     1.nonzero?                    1.singleton_method_added      1.truncate&lt;br /&gt;1.divmod                      1.instance_eval               1.object_id                   1.singleton_methods           1.type&lt;br /&gt;1.downto                      1.instance_exec               1.odd?                        1.size                        1.untaint&lt;br /&gt;1.dup                         1.instance_of?                1.ord                         1.step                        1.upto&lt;br /&gt;1.enum_for                    1.instance_variable_defined?  1.prec                        1.succ                        1.zero?&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;You may scope down results by typing more, say, show all instance methods that start with 'i'.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;irb(main):001:0&gt; 1.i&lt;br /&gt;1.id                          1.instance_eval               1.instance_variable_defined?  1.instance_variables          &lt;br /&gt;1.id2name                     1.instance_exec               1.instance_variable_get       1.integer?                    &lt;br /&gt;1.inspect                     1.instance_of?                1.instance_variable_set       1.is_a?          &lt;/code&gt;&lt;br /&gt;&lt;br /&gt;To enable tab completion in irb, you need to start irb with -r irb/completion option.  Or if you are already in irb, do 'require irb/completion'.&lt;br /&gt;&lt;br /&gt;As a bonus, require irb/completion works in rails script/console too.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-3316981238765646636?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/3316981238765646636/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=3316981238765646636' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/3316981238765646636'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/3316981238765646636'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2009/02/irb-with-autocompletion-support.html' title='irb with autocompletion support'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-7767833394061090805</id><published>2009-01-24T05:40:00.000-08:00</published><updated>2009-01-24T06:03:35.123-08:00</updated><title type='text'>How to make Ruby and JRuby live peacefully</title><content type='html'>Similar to each Ruby versions, Ruby and JRuby maintain their own gems separately.  While we can use jruby and jirb to specifically tell we want to JRuby version, JRuby does not have jrake or jgem.  How do we specify we want to execute rake/gem in Ruby and JRuby?&lt;br /&gt;&lt;br /&gt;A solution is to prefix the program with ruby -S and jruby -S like&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;ruby -S rake&lt;br /&gt;jruby -S rake&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;or &lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;ruby -S gem list&lt;br /&gt;jruby -S gem list&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;This way, we explicitly tell which interpreter we want to use and it will automatically find the right program in the right path.  Problem solved.&lt;br /&gt;&lt;br /&gt;If you want to install multiple Ruby vesions in the same machine, use MultiRuby as described in Dr Nic's &lt;a href="http://drnicwilliams.com/2008/12/11/future-proofing-your-ruby-code/"&gt;Future proofing your Ruby code. Ruby 1.9.1 is coming.&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-7767833394061090805?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/7767833394061090805/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=7767833394061090805' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/7767833394061090805'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/7767833394061090805'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2009/01/how-to-make-ruby-and-jruby-live.html' title='How to make Ruby and JRuby live peacefully'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-4296691980597111677</id><published>2008-11-30T06:05:00.000-08:00</published><updated>2008-11-30T08:43:39.721-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='bdd rspec ror'/><title type='text'>Finding which rspec tests produce unexpected outputs</title><content type='html'>You know running hundred of tests should only show '.', 'F', or 'E' and nothing more.  You feel disturbed when some passing tests print debugging statements or rspec matcher complains that one of erb/rhtml views do not have a closing html tag and print a bunch of html outputs.  &lt;br /&gt;&lt;br /&gt;You want to find which tests among hundreds produce these but you have no clue where to find them.  You don't want to search for 'puts', 'p' or 'inspect' from the entire codebase.  Nor would you want to find which erb/rhtml files have missing closing tags. What should you do?&lt;br /&gt;&lt;br /&gt;My colleague, Toby, suggested me to look at rspec source code, specifically at the formatters so that we can find a spot that runs examples and shows the '.' output.  So I did and found the progress_bar_formatter.rb in lib/spec/runner/formatter.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;        def example_passed(example)&lt;br /&gt;          @output.print green('.')&lt;br /&gt;          @output.flush&lt;br /&gt;        end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;We can put a print statement to identify which example (rspec test) is passing.  Either @output.print example.description or @output.print example.inspect should be fine.  Once we know the example names, we should be able to find where they are.  Now we can fix the problem and make all test outputs produce those little green dots.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-4296691980597111677?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/4296691980597111677/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=4296691980597111677' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/4296691980597111677'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/4296691980597111677'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2008/11/finding-which-rspec-tests-produce.html' title='Finding which rspec tests produce unexpected outputs'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6888658749995617133.post-291606609709733686</id><published>2008-11-23T16:05:00.000-08:00</published><updated>2008-11-23T16:26:00.036-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ruby'/><title type='text'>Ruby: Treat object and collection uniformly</title><content type='html'>Problem: You write a method that takes a collection and iterates over it.  However, you also want to accept a single object parameter as well. &lt;br /&gt;&lt;br /&gt;Solutions:  Convert a single object into an array so that we can manipulate the parameter uniformly.  As always, there are many ways to do this in Ruby.  However, I prefer the last one.&lt;br /&gt;&lt;br /&gt;1. Make sure it is an array by using Object#to_a.  However, to_a is deprecated and not recommended.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;def f(a)&lt;br /&gt;  a = a.to_a&lt;br /&gt;  a.each { |item| ... }&lt;br /&gt;  ...&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;2. Check the parameter type and wrap it into an array if it is not an array already.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;def f(a)&lt;br /&gt; a = [a] if a.is_a? Array&lt;br /&gt; ...&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;3. Duck-type check whether it responds to :each method&lt;br /&gt;&lt;br /&gt;&lt;code&gt;def f(a)&lt;br /&gt; a = [a] unless a.respond_to? :each&lt;br /&gt; ...&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;4. Use splat operator.  This also does the job.  It is concise but less readable.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;def f(a)&lt;br /&gt; a = [*a]&lt;br /&gt; ...&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;5. Use Array#flatten.  I prefer this one.  It is readable.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;def f(a)&lt;br /&gt; a = [a].flatten&lt;br /&gt; ...&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt; &lt;br /&gt;&lt;br /&gt;Is there any other more way?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6888658749995617133-291606609709733686?l=weewillrockyou.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://weewillrockyou.blogspot.com/feeds/291606609709733686/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6888658749995617133&amp;postID=291606609709733686' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/291606609709733686'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6888658749995617133/posts/default/291606609709733686'/><link rel='alternate' type='text/html' href='http://weewillrockyou.blogspot.com/2008/11/ruby-treat-object-and-collection.html' title='Ruby: Treat object and collection uniformly'/><author><name>Weerasak</name><uri>http://www.blogger.com/profile/04042457149790214773</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='21' height='32' src='http://4.bp.blogspot.com/_1nPe_hIK-9w/SSn1JmVmSaI/AAAAAAAAAOQ/QVUiGAsD3c8/S220/IMG_0039.JPG'/></author><thr:total>0</thr:total></entry></feed>
