2008年4月30日 星期三
error handling: rescue & raise
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
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)
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"}
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:
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
math methods
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)
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”]