为什么第二个输出只显示Array
的一个元素?它仍然是Array
或Hash
吗?
def printArray(arr)
arr.each { | j |
k, v = j.first
printf("%s %s %s \n", k, v, j)
}
end
print "Array 1\n"
printArray( [
{kk: { 'k1' => 'v1' }},
{kk: { 'k2' => 'v2' }},
{kk: { 'k3' => 'v3' }},
])
print "Array 2\n"
printArray( [
kk: { 'k1' => 'v1' },
kk: { 'k2' => 'v2' },
kk: { 'k3' => 'v3' },
])
exit
# Output:
#
# Array 1
# kk {"k1"=>"v1"} {:kk=>{"k1"=>"v1"}}
# kk {"k2"=>"v2"} {:kk=>{"k2"=>"v2"}}
# kk {"k3"=>"v3"} {:kk=>{"k3"=>"v3"}}
# Array 2
# kk {"k3"=>"v3"} {:kk=>{"k3"=>"v3"}}
答案 0 :(得分:5)
Ruby将第二个示例解释为一个数组,其中包含一个哈希作为其元素(隐含花括号)。它相当于:
[{ kk: { 'k1' => 'v1' }, kk: { 'k2' => 'v2' }, kk: { 'k3' => 'v3' }}]
仅显示最后一个'kk'
,因为哈希不能包含重复键;只有最后一个坚持。
如果您想要一个包含多个哈希值的数组作为元素,则需要使用第一个示例中的语法。
更多关于ruby暗示哈希开始的例子:
# Only argument on method calls
def only_arg(obj)
puts obj.class
end
only_arg(bar: "baz") # => Hash
# Which is equivalent to:
only_arg({bar: "baz"}) # => Hash
# Last argument on method calls
def last_arg(ignored, obj)
puts obj.class
end
last_arg("ignored", bar: "baz") # => Hash
# Which is equivalent to:
last_arg("ignored", { bar: "baz" }) # => Hash
# Last element on an array
def last_on_array(arr)
puts arr.last.class
end
last_on_array(["something", "something", bar: "baz"]) # => Hash
# Which is equivalent to:
last_on_array(["something", "something", { bar: "baz" }]) # => Hash