Ruby打å°å“ˆå¸Œçš„所有元素但最åŽ

时间:2014-02-15 18:32:21

标签: ruby hash key

说我有:

hash = {"a" => 1, "b" => 2, "c" => 3}

keys = hash.keys

为了打å°ä½ è¦åšçš„所有按键:

keys.each {|x| puts x}

我的问题是,你怎么打å°æ‰€æœ‰çš„键但是最åŽä¸€ä¸ªï¼Ÿ

2 个答案:

答案 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æ¥èŽ·å–最åŽä¸€ä¸ªå…ƒç´ ã€‚