2008年5月2日 星期五

date and time method

require 'date'
require 'time'

Time.now  or Time.new
-->  Fri May 02 16:50:08 +0800 2008

Time.now.strftime('%Y-%m-%d')
-->  "2008-05-02"

SECOND_IN_A_DAY

兩個時間相減得到的單位是秒 


Date.today:


%Y, %y:  year

%b, %B: month

%m : month(number)

%d, %e:  day of month

%a, %A: dat name( such as Tue)

%H, %I: hour

%M: minute

%S: second

%c:  equals "%a %b %d %H:%M:%S %Y"

%x:  equals "%m/%d/%y"

2008年5月1日 星期四

block and yield

yield: 
run what block defines
ex:
def  test(*args, &block)
        yield(*args)
end
test("hello"){ |i| puts i }
---> hello

note:
yield(*args)  = block.call(*args)

when defining a method that receives blocks,
there are two ways
(1)  define method with block arguments
ex:
def test( &block)
end

(2)define method without block arguments
ex:
def test
end

pass arguments to blocks
in the method definition, call yield with arguemtns
ex:
yield (a, b, c)

in the block, use | | to receive arguments 
ex:
| a, b, c|

return value from call block
the return value is last expression evaluated in block
ex:
in the method definition
a= yield

here doc

build up a long string


ex:

NAME= <<END_MY_STRING

      hello

      how are you

END_MY_STRING


puts NAME

--->   hello

         how are you

required, optional, default-valued parameters

required parameter:

def  test1( name)


end


default value parameter

def  test2(name=”peter”)


end

呼叫test2時,若是沒傳參數,則name=”peter”, 

若是傳參數”andy”,則name=”andy”


optional parameter

use *

ex:

def test(*abc)

end

abc可接受多個參數,以array表示

例如呼叫test(1,2)

則p abc 印出 [1, 2]

note: optional parameter must be last parameter of the method

block, proc and &

call method with block parameter:
two syntaxes:
1.  {   } 
     this is useful for one line
2. do   end
    this is useful for multiple line
ex:
["a", "b"].each do |i|
    puts "#{i}"
end
the element between |  | refers to each element in the array  

define a method with block parameter
use &
ex:
class Array
     def test( &arg)
           find_all( &arg)
     end    
end

pass proc parameter to a method received block
ex:
a=lambda{ puts "abc"}
test(&a)

lambda and proc

lambda:
parameter:  block
return: an instance of class Proc

Proc:
procedure
method:  
call:
tell proc to do sth

ex:
test = lambda { |i| i + 1 }
test.call(2)
--> 3

the method to pass parameters
1. test.call(2) 
2.  test[2]

another method to create Proc:
Proc.new {   }

IDE

textmate : 
mac, not free

aptana studio: 
 mac & windows, free
 include RadRails

3rdRail:  
mac & windows, free

NetBeans:
mac & windows, free