2008年5月1日 星期四

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

2008年4月30日 星期三

web api

open-uri
get date from URI
add   require 'open-uri'   in the program

YAML

load:
ex:
YAML.load(File.open("test.yaml") )
return the content in test.yaml
such as  "name:  peter" return  'name'=>'peter'

dump:
write to YAML file
ex:
File.open("test.yaml", w) {  |output|  YAML.dump(names, output) }

error handling: rescue & raise

handle exception:

ex:
begin
      puts  1/0
rescue
     puts "error"
end
--->  "error"

rescue can for specific exception:
ex:
begin
     puts 1/0
rescue  ZeroDivisionError
     puts "error"
end

rescue for method
ex:
def test
    puts "test"
rescue
    puts "rescue"
end
       
raise
raise exception
ex:
def test
   raise  ArgumentError,  "argument error"
end
the second argument is the message printed

get the exception
ex:
rescue ArgumentError =>  e
e is the exception 

define exception
ex:
class  TestException  <>
end

range

ex:

(‘A’..’Z’)


ex:

0..9