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"}
沒有留言:
張貼留言