Coding is an Art

Anoiaque::Ergasterium

20/10/2010

Install ruby 1.9.2 on snow leopard : readline compile error

Even if i had readline installed on my system in /usr/local, i still get the same (readline) error at compile of ruby 1.9.2 when i try to install it with rvm.

I remedy that compile error like that:

  • (re)install libxml2:
  • tar xzvf libxml2-2.7.3.tar.gz  
    cd libxml2-2.7.3 
    ./configure --with-python=/System/Library/Frameworks/Python.framework/Versions/2.3/ 
    make 
    make install
  • (re)install readline
  • curl -O ftp://ftp.cwru.edu/pub/bash/readline-6.0.tar.gz
    tar xvf readline-6.0.tar.gz
    cd readline-6.0
    ./configure && make && make install
  • Then install readline via rvm package :
  • rvm package install readline  

17/10/2010

Recursive Hash#sort and Array#to_hash

Ruby standard Hash#sort method does not sort recursively an hash.
Here is a method that do the job.
It recursively sort the hash using Array#sort and return the sorted array.


 class Hash
   
    # Return array from hash recursively sorted
    def to_sorted_array block=nil
      sort(&block).inject([]) do |array, (key, value)|
        value = value.is_a?(Hash) ? value.to_sorted_array : value
        array << [key, value]
      end
    end
    
  end


hash={'user' => {'adress' => {'town' => 'Paris', 'street' => "rue de Quimper"}, 'name' => 'toto', 'age' => 12}}
hash.to_sorted_array # =>
[["user", [["adress", [["street", "rue de Quimper"], ["town", "Paris"]]], ["age", 12], ["name", "toto"]]]]



The Array#to_hash ruby standard method do not transform an array into an hash equivalent, recursively.
Here is a method which do the job:

class Array
  # Recursively convert array to hash 
  def to_hash 
    inject({}) do |hash, (key, value)|
      value = value.to_hash if value.kind_of?(Array)
      hash.merge!({key => value})
    end
  end
    
end

  array = [["user", [["adress", [["street", "rue de Quimper"], ["town", "Paris"]]], ["age", 12], ["name", "toto"]]]]
  array.to_hash
  
  {"user"=>  {"name"=>"toto", "adress"=>{"street"=>"rue de Quimper", "town"=>"Paris"}, "age"=>12}}

I' ve put these extensions into a library on github : ruby_extensions

To install the gem :
gem install ruby_extend

Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it.
Alan Perlis


The best way to predict the future is to invent it.
Alan Kay


Ne découvre de nouvelles terres que celui qui sait quitter tout rivage.
André gide


Qui ne doute pas acquiert peu
Léonard de Vinci


Our life is frittered away by detail... simplify, simplify.
Henry David Thoreau