说我有:
hash = {"a" => 1, "b" => 2, "c" => 3}
keys = hash.keys
为了打å°ä½ è¦åšçš„所有按键:
keys.each {|x| puts x}
æˆ‘çš„é—®é¢˜æ˜¯ï¼Œä½ æ€Žä¹ˆæ‰“å°æ‰€æœ‰çš„键但是最åŽä¸€ä¸ªï¼Ÿ
ç”案 0 :(得分:0)
hash = {"a" => 1, "b" => 2, "c" => 3}
keys = hash.keys
keys[0..-2]
#=> ["a", "b"]
[0..-2]
会将数组从最åŽä¸€ä¸ª
keys[0..-2].each { |x| puts x }
å¯ä»¥é€šè¿‡è°ƒç”¨æ•°ç»„上的last
方法æ¥æ£€ç´¢æ•°ç»„ä¸çš„最åŽä¸€ä¸ªå…ƒç´
keys.last
#=> "c"
ç”案 1 :(得分:0)
我会使用Enumerable#take
执行以下æ“作:
hash = {"a" => 1, "b" => 2, "c" => 3}
hash.take(hash.size-1).each do |k,_|
p k
end
# >> "a"
# >> "b"
或者,如下所示:
hash = {"a" => 1, "b" => 2, "c" => 3}
hash.keys.take(hash.size-1) # => ["a", "b"]
puts hash.keys.take(hash.size-1)
# >> a
# >> b
更新(按照OPçš„è¦æ±‚ - 好了,现在我如何æ‰èƒ½æ˜Žç¡®æ‰“å°æœ€åŽä¸€ä¸ªå…ƒç´ ?)
hash = {"a" => 1, "b" => 2, "c" => 3}
hash.keys.last # => "c"
Hash#keys
会将该哈希的所有键作为数组æä¾›ç»™æ‚¨ã€‚æ‰€ä»¥ï¼ŒçŽ°åœ¨ä½ å¯ä»¥åœ¨è¯¥æ•°ç»„上调用Array#last
æ¥èŽ·å–最åŽä¸€ä¸ªå…ƒç´ 。