2008年4月30日 星期三

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 }



沒有留言: