我正在尝试使用下面的代码仅在密钥是整数时才在哈希中保留值。我在这里做错了什么?
hackerrank.keep_if do |x,y| x.is_a? Integer end
编辑:我必须做错事,因为我一直在HackerRank.com上遇到运行时错误。我的完整代码如下:
hackerrank.store[543121,100] # store new key-value pair
hackerrank.keep_if { |x,y| x.is_a?(Integer) } # keep if key is an integer
hackerrank.delete_if { |x,y| x % 2 == 0 } # delete if key is even
编辑2:此处提供了与挑战的链接:https://www.hackerrank.com/challenges/ruby-hash-add-del-sel
答案 0 :(得分:3)
它需要看起来像这样(括号,而不是方括号):
hackerrank.store(543121, 100)
#=> 100
答案 1 :(得分:1)
尝试 -
hackerrank[543121] = 100 # store new key-value pair
hackerrank.keep_if { |x,y| x.is_a?(Integer) && x.odd? } # keep if key is an integer and not even
或者使用@ seph的建议https://stackoverflow.com/a/31018495/2545197尝试使用您的代码 -
hackerrank.store(543121,100) # store new key-value pair
hackerrank.keep_if { |x,y| x.is_a?(Integer) } # keep if key is an integer
hackerrank.delete_if { |x,y| x % 2 == 0 } # delete if key is even
答案 2 :(得分:0)
# store expects two parameters, let‘s
# ⇓ splat an array
hackerrank.store *[543121, 100]
# let’s select everything we are interested in
# inplace ⇓ only integers ⇓⇓⇓ odds ⇓⇓⇓⇓
hackerrank.select! { |(k,v)| Integer === k && k.odd? }