分段错误和Ruby语法澄清

时间:2014-06-04 03:34:39

标签: ruby

我的代码出错:

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.newhash会收到一个阻止。 hash[key] = if key < coins.min是什么意思? key从哪里获取价值?这个= if条件是什么?

1 个答案:

答案 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::newHash#[]以及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