我的代码出错:
o = Hash.new do |h,k|
h[k]
end
o[1] # => [BUG] Segmentation fault at 0x007fff5f3fff80
<小时/> 试图了解this code正在做什么:
optimal_change = Hash.new do |hash, key|
hash[key] = if key < coins.min
[]
elsif coins.include?(key)
[key]
...
o = Hash.new
和hash
会收到一个阻止。 hash[key] = if key < coins.min
是什么意思? key
从哪里获取价值?这个= if
条件是什么?
答案 0 :(得分:2)
在第一种情况下,由于永不结束递归,您的 IRB 崩溃了。你做了
o = Hash.new { |h,k| h[k] }
o[1]
在这里,您尝试访问已分配给1
的哈希的键o
的值。现在,当你进行o[1]
时,你将被调用,在块中你再次执行h[1]
,它再次调用同一个块,同样重复并且它将进入永无止境的递归,所以错误出来了。但错误应该是堆栈级别太深(SystemStackError)。
Hash::new
并且hash[key]
,hash
将不在场。
但在第二种情况下,您将值分配给分配给key
的哈希对象的键,具体取决于相同条件,如果键当您执行o
时,strong>尚未添加到O
。因此,不会有无限递归。
o[:key]
阅读此Hash::new
和Hash#[]
以及Hash#[]=
方法。
示例: -
# result of the if-else block will be assigned to the **key** of the **hash**.
hash[key] = if key < coins.min # some condition check is being performed here.
[] # then an empty is being assigined to the hash[key]
elsif coins.include?(key) # again a condition test
[key] # if true this value will be returned.
else
# some vale, which you didn't show us. If it is not present, and
# no condition will be evaluated as true, there is a definite infinte
# recursion will be happened again.
end