Archive

Archive for the ‘ruby’ Category

Ruby Arrays and Hashes

January 5, 2007 Gaurav Sohoni Leave a comment

Came to know about these :

Inject method:

Say you have an array a1 = [1,2,3,4,5] and you want to sum up the elements, then do this -

a1.inject(0) {| sum_so_far, item | sum_so_far + item}

This iterates over all the five elements and returns 15.

To find the product:

a1.injetc(1) { | product, item| product * item}

Collect method:

An array, a = [1, 2, 3]

a.collect {|element| element * 2}

This iterates over [1, 2, 3] and doubles it up to give…(no prizes for guessing)

Partition Method:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

odd_and_even = numbers.partition {|number| number % 2 == 1}

Result = [[1, 3, 5, 7, 9], [2, 4, 6, 8]]

Map method:

array = %w{one two three four}

array.map {| word | word.capitalize}

Result = ["One", "Two", "Three", "Four"]

Categories: ruby Tags: , , ,

Letz Talk Ruby and Rails

December 23, 2006 Gaurav Sohoni Leave a comment

This is about Ruby and of course Rails. So lets get onto Ruby on Rails wagon.

These are some things that I keep using these days:

To check for empty file field:
@image = Image.create params[:image] unless params[:image][:file_data].kind_of? StringIO

here params[:image][:file_data] is the hash for image to be loaded.
If the file field is blank, for :file_data => #<StringIO:0×677cf1c>

Using joins for finding required records:
* A belongs to B

@items = A.find(:all, :conditions => “bs.name like ‘%#{@to_search_for}%’”,
:joins => “left join bs on b_id = bs.id”)
* A belongs to B and B belongs to C

@items = A.find(:all, :conditions => “cs.name like ‘%#{@to_search_for}%’”,
:joins => “left join bs on b_id = bs.id ” +
“left join cs on c_id = cs.id”)
as, bs and cs being the plural forms of a,b and c and hence used as table names.

How to use javascript to go one step back in history pages:
<a href=”javascript:history.go(-1)”>Back</a>

How to add two submit buttons to one form and perform 2 differenr functions:

<%= form_remote_tag :url => {:action => ‘update_info’, :id => @info} %>
<%= render :partial => ‘form’ %>
<%= submit_tag ‘Add Pro’, :name => ‘pro’ %>
<%= submit_tag ‘Add QA’, :name => ‘qa’ %>
<%= end_form_tag %>

check for two submit tag :name attributes in params in controller and do specific task.