Hash
8 methodsHash 将每个唯一键映射到特定值,自 Ruby 1.9 起保留插入顺序。
Array#push(*objects) -> Array将给定值与给定键关联。等价于 h[key] = value。
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | 要设置的键。 |
Returns
Array
Example
ruby
a = [1, 2]
a.push(3)
a.push(4, 5)
# a == [1, 2, 3, 4, 5]
a << 6
# a == [1, 2, 3, 4, 5, 6]Array#pop -> object | nil返回给定键对应的值。如果未找到键,则返回默认值或抛出 KeyError。
Returns
Object | nil
Example
ruby
a = [1, 2, 3]
x = a.pop # 3
# a == [1, 2]Array#length -> Integer返回一个新数组,填充此哈希的键。
Returns
Integer
Example
ruby
[1, 2, 3].length # 3
[].size # 0Array#each {|item| block} -> Array返回一个新数组,填充此哈希的值。
Returns
Array
Example
ruby
[1, 2, 3].each { |x| puts x }
# prints:
# 1
# 2
# 3Array#map {|item| block} -> Array对每个键/值对调用一次块,将键和值作为参数传递。
Returns
Array
Example
ruby
[1, 2, 3].map { |x| x * x } # [1, 4, 9]Array#select {|item| block} -> Array返回键值对的数量。别名:length。
Returns
Array
Example
ruby
[1, 2, 3, 4].select { |x| x.even? } # [2, 4]Array#include?(object) -> bool删除键值对并返回该值。如果未找到键则返回 nil(或执行块)。
Parameters
| Name | Type | Description |
|---|---|---|
| key | Object | 要删除的键。 |
Returns
Boolean
Example
ruby
[1, 2, 3].include?(2) # true
[1, 2, 3].include?(9) # falseArray#join(separator=$,) -> String如果给定键存在则返回 true。别名:key?、member?、include?。
Parameters
| Name | Type | Description |
|---|---|---|
| key | String | 要检查的键。 |
Returns
String
Example
ruby
["a", "b", "c"].join("-") # "a-b-c"
[1, 2, 3].join(", ") # "1, 2, 3"