0

为什么第二个输出只显示一个元素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"}}
4

1 回答 1

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
于 2013-11-08T23:28:43.380 回答