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


define class

ex:

class Rabbit

    def  initialize( name)

        @name = name

    end


    def run 

        puts “run”

    end

end


initialize:

this method is called when the object is created

this is a private method. Hence, when using new to create object, the new method will call initialize 


instance variable:

the variable that starts with @ is instance variable


naming convention:

class name:  CuteRabbit

file name : cute_rabbit.rb


private:

the method is private

define methods after private

ex:

private  

def  test

end


protected:

the method is protected


modify existing class

ex:  the Array is built-in class.

class Array

    def test

    end

end

now the Array has new method test


class variable:

the variable that starts with @@ is class variable


class method:

ex:

def self.test

end


inheritance:

ex:

class Circle  < Shape


end


if class Square is defined inside class Shape, you must access Square with

Shape::Square outside class Shape

ex:

class Test  < Shape::Square


end


constant in the class

if TEST is the constant of class Rabbit,

we can access Test using Rabbit::Test


constant

use capital letter

ex:

Apple,  Rabbit


access constant define in class

ex:

Name is defined in the class Rabbit

Rabbit::Name

hash

hash is declared inside { }

ex:

animal= { 

    :one=> “dog”,

    :two=>”rabbit”

}

說明:

animal[:one] = “dog”

animal[:two]=”rabbit”


ex:

animal= {

    :one=>[‘v’, ‘version’ ]

}


CONSTANT is often defined as hash

ex:

OPTIONS={

    :command=>[‘r’, ‘run’]

}


keys:

return the keys of hash in the array

ex:

{ :a=>”name”, :b=>”age”}.keys

-->  [ :a,  :b ]


values:

return the values of hash in the array

ex:

{ :name=>"peter"}.values

--->  ["peter"]


values_at

get multiple element

ex:

{ :a=>"a", :b=>"b", :c=>"c"}.values_at(:a,:b)

---> ["a", "b"]


has_key? :

ex:

{:a=>"a"}.has_key?(:a)

--->  true

sort_by:

由小排到大

ex:

a={ :c=>"C", :b=>"B" }

a.keys.sort_by{ |i| a[i] }

---> [:b, :c]


ex:

sort_by{ |a, b| }

sort according to a first, according to b in case of a tie


merge:

ex:

{ :a=>"a", :b=>"b"}.merge( {:a=>"c", :d=>"d" } )

-->  { :a=>"c", :d=>"d",  :b=>"b" }


each_key:

ex:

c= { :a=>"aa", :b=>"bb"}

{ :a=>"aa", :b=>"bb"}.each_key { |i| puts c[i] }
-->  aa
      bb

each_pair:
{ "name"=>"peter"}.each_pair do |i,j|
     puts   i+ " "+ j
end
---> name peter

sort:
return nested array
default(without pass block parameter) :
ascending order  & compare hash's value

ex:
{ "b"=>1,  "a"=>2}.sort
--> [ ["b", 1],  ["a", 2] ]

Hash.new(0)
set default value of hash for nonexistent keys, the key is still nonexistent
ex:
a =Hash.new(0)
a[2]
--->  0
set default value of hash for nonexistent keys, the key is added
ex:
a=Hash.new { |hash, key| hash[key]=0 }



RDoc

=begin rdoc

    RDoc comments

=end


allow HTML-like tagging

each, each_with_index, map

each:

accept block parameter that describe what to do with each element of array or hash


ex: 

[“A”, “B”].each do |i|

       puts “#{i}”

end

--->  A

        B


each_index:

ex:

["A", "B"].each_index do |i|
    puts "#{i}"
end

each_with_index:

ex:

['a','b','c'].each_with_index do |content, index|

puts "#{content}#{index}"

end

---> a0

       b1

       c2


map:

v.s each: different in return 

it return the new value, each return original value

ex:

[1,2,3].map{ |i| i*2 }

--->[2,4,6]

map! will change content of caller


array

enclosed with [ ]

 

can contain elements with different classes

  

add element to array:

use <<

ex:

a=[]

a <<>


array adding
ex:
[“test1”] + [“test2”]
-->  [ “test1”,  “test2” ]

use concat:

ex:

[1,2].concat([3,4])

--> [1,2,3,4]

concat modifies original array



<<:

add element to array

ex:

a=[1,2]

a<<3

---> [1,2,3]


new:

ex:

Array.new(3, "a")

create a three element array ,with each initialized to "a"

a=0

Array.new(3) { a=a+1 }

create a three element array , [1,2,3]


get more than one elements

ex:

a=[1,2,3,4,5]

a[3,2] 

--->  [4,5]



sort_by

accept block argument

ex:

sort_by{ rand }

sort randomly 


join:

[“a”, “b”, “c”].join(‘2’)

-->  “a2b2c”


push:

add an element to the end of the array


pop:

remove last element


include:

ex:

[1, 2, 3].include?(1)

--->  true


uniq:

ex:

["ab", "c","ab"].uniq

--->["ab", "c"]


multiplication:

ex:

[1,2]*2

--> [1,2, 1,2]


detect:

find the first element that match condition in the array

ex:

[1 , 2, 3].detect { | i |  i>2 }

--> 3


find:

find first element that matches  


find_all:

find all elements that match condition in the array

ex:

[1,2,3].find_all{ |i| i>1 }

-->  [2, 3]


array intersection:

use &

ex:

[1,2,3] & [2,3]

--> [2,3]


%w[a b]

--> ["a",  "b"]


sort:

ex:

c=[ [1, 2], [3, 1] ]

c.sort{ |a, b| a[0]<=>b[0] }

-->  [ [1,2], [3, 1] ]

c.sort{ |a, b| b[0]<=>a[0] } 

-->   [[3, 1], [1, 2]]

c.sort{ |a, b| a[1]<=>b[1] } 

-->   [[3, 1], [1, 2]]


a[0] <=> b[0] compare first element of nested array in ascending order

a[1] <=> b[1] compare second element of nested array in ascending order

b[0] <=> b[1] compare first element of nested array in descending order


unshift:

add an element to the beginning of the array


shift:

remove the first element 


zip:

ex:

[1,2].zip([3,4])

--> [ [1,3],  [2,4] ]


flatten:

ex:

[1,2, [3,4] ].flatten

--> [1,2,3,4]


reject:

ex:

[1,2,3].reject { |item|  item>2 }

---> [1,2]


replace, reverse:


each, each_with_index


include?,  empty?, any?, all?

ex:

[1,2,3].any?{ | k|  k>2 }

---> true


index:

return the first element equals to parameter

ex:

["a", "b", "c"].index( "b")

---> 1


index   with  integer <0

count from right

ex:

a= [1, 2, 3]

a[-1]  

--->  3


compact:

remove nil element from the array

regular expression

use /  /  to include regular expression

ex:

/a/


test regular expression match:

use =~

ex: 

“hello”=~ /el?/

--->  1


? :

zero or more occurrence 


+:

one or more occurrence


\W:

any whitespace


\{X}:

ex:

a{3}

-->  three  a


\d:

any digit


\:

treat the special character after it as normal character 


^ :

anchor for the beginning of a line


$:

anchor for the end of a line


*:

match 0 or more occurrences of preceding character 


Regexp.new:

ex:

Regexp.new("test")

---> /test/

string method


crate string array

ex:

%w[AB CD]

---> [“AB”, “CD”]


gsub & gsub!:

global substitution 

ex:

"hello".gsub("e","a")

--->  "hallo"

gsub! will change original string


gsub & sub:

gsub change every match, sub only change first match

ex:

"helleo".gsub("e","a")

--> "hallao"

"helleo".sub("e","a")

--> "halleo"


sprintf:

ex:  

sprintf(“%2d”, 3)

--> “  3”


inject:

ex:

[1, 2,3].inject(10) {  | sum, number|  sum=sum+number }

--> 16

inject初始sum為10,

然後10+1=11

11+2=13

13+3=16


chomp:

remove the newline character


chop:

remove last character 


grep:

ex:

["test", "b", "testa", "test"].grep("test")

--->["test", "test"]


split:

ex:  

“hello”.split(‘e’)

 --->["h", "llo"]

ex:   

a, b= "hello".split('e')

--> a= "h", b="llo"


chr:

a= "abcde"

a[0].chr

-->  "a"


strip:

return a copy with leading and tailing whitespace removed


lstrip & rstrip

removing left or right whitespace 


%q :

create string, single-quoted

ex:

%q (abc)

---> "abc"


%Q: 

create string, double-quoted 


\ :

use \ to escape:

ex:

puts "abc\"de"

--->  abc"de


<<:

add string(modify original string)

ex:

a="test"

a<< "abc:

puts a

-->  testabc


replace:

ex:

a="test"

a.replace("abc")

puts a

---> abc


reverse,  downcase, upcase, capitalize, swapcase 


substring:

ex:

"abcde"[2,2]

--->  "cd"

a="abcde"

a[2,2]="gg"

a

---> "abgge"


succ:

ex:

"abc".succ

--> "abb"


%:

format string

ex:

"%.2f"%3.333

--->"3.33"

module

 module is like class,  but it can not be instantiated
 support methods for other class
 
use include to include module

a class can only have inherit from one class, but it can mix in more than one mouels

ex:
module Animal
    def   test
    ned
end 

class Rabbit
      include Animal
      def  run
           test
     end
end

if a class include two modules,  M1 & M2( M2 is included last),
M1 & M2 both have method test
When the object of the class calls method test,
it will call M2's test

require

use external file

ex:
require 'test'
t= Test.new

Test class is defined in another file( test.rb)

math methods

abs:
ex:
-3.abs
--> 3

zero?
tell if the number is zero
ex:
3.zero?
--> false

rand:
ex:
rand(100)
return an random integer from 0 to 99

round:
ex:
3.1.round 
--> 3
3.5.round 
--->4

useful utilities (irb, ruby)

irb:

    a shell to run ruby 


    irb  -r  test.rb

    include the content of test.rb,  r is require


ruby:

-w:

turn warnings on for your script

-e:

execute the code in '  '

ex:

ruby -e  'puts "hello"  '

--->  hello

-r:

require some files

-rdebug:

debug program,

step command:  run next instruction 

-r profile:

test performance

useful methods

methods:

show the methods of this object

ex:

10.methods


dup:

make a copy of original object

ex:

“test”.dup


reverse:

ex:

"test".reverse

--->"tset"


match:

ex:

match:

“test”.match(“es”)


not match:

“test”.match(“ed”)


is_a?:

decide if the object is this type

ex:

"test".is_a?(String)

---> true

ancestors:
ex:
Integer.ancestors
-- [Integer, Precision, Numeric, Comparable, Object, Kernel]

inspect
return the string representation of object
ex:
[1,2,3].inspect
--> "[1,2,3]"
note:  p  [1,2,3]  equals [1,2,3].inspect

superclass:
class method, tell the superclass of  class

to_proc ( &: )

turn the symbol into proc

test= rabbit.map{ |name|  name.upcase }

is the same as 

test= rabbit.map{ &:upcase }


example on rails:

rabbits= Rabbit.find(:all)

//   show the name of rabbits

method 1
 rabbits.collect { |t|  t.name }

method 2
rabbits.collect( &:name)


//  show the name of rabbits using downcase

rabbits.collect(&:name).collect(&:downcase)


all? and any?

all?  

if code block to each element of array or hash is true, then return true

ex:

rabbits.all?( &: valid? )


any?

accept block, if code block to any element of array or hash is true, then return true

ex:

[1,2, 3].any? { |i|  i>2  }

-->  ture

2008年4月29日 星期二

casting ( change type)

to_s:  change to string

ex:

10.to_s

--> “10”


to_i: change to integer

ex:

“10”.to_i

-->  10

ex:

"1a".to_i(16)

---> 26 




to_a: change to array

ex:

(‘1’..’3’).to_a

-->  [“1”, “2”, “3”]