Nested hash in ruby

Ever wondered how to create nested hash in ruby?

Here it is:

1.9.3p125 :001 > a = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc) }

 => {} 

1.9.3p125 :002 > a[2][1] = 2

 => 2 

1.9.3p125 :003 > a[2][2][3] = 2

 => 2 

1.9.3p125 :004 > a[2][2][4] = 5

 => 5 

1.9.3p125 :005 > a[3][1][1][1] = 7

 => 7 

1.9.3p125 :006 > a

 => {2=>{1=>2, 2=>{3=>2, 4=>5}}, 3=>{1=>{1=>{1=>7}}}} 

:) sweet!

Quick and dirty search in Rails

Ever wondered how to quick have a search function in your rails app?

Here is a super quick and maybe a lil dirty way to achieve so.

First step:

The view


 <p><%= form_tag("/searches", :method => "get") do %>

           <%= text_field_tag :keywords, params[:keywords] %> </p>

       <p>  <%= submit_tag("Search") %>

           <% end %>

       </p>

Second step:

search.rb model (app/models)

class Search < ActiveRecord::Base

  def self.find_results(search)

    if search

      Item.find(:all, :conditions => ['name LIKE ?', "%#{search}%"])

    else

      Item.find(:all)

    end

  end

end

Third step:

searches_controller.rb (app/controllers)

class SearchesController < ApplicationController

  def index

    @results = Search.find_results(params[:keywords])

  end

end

Fourth step:

index.html.erb (app/views/searches)

<% @results.each do |result| %>

             <p><%= result.name %></p>

Done :)

Just don’t forget to add   resources :searches, :controllers => ‘searches’ to your routes.rb!