加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的默认哈希值(Rubykoans.com – > about_hashes.rb)

发布时间:2020-12-16 21:47:29 所属栏目:百科 来源:网络整理
导读:我从 RubyKoans开始经历about_hashes.rb.1练习让我感到困惑: def test_default_value hash1 = Hash.new hash1[:one] = 1 assert_equal 1,hash1[:one] #ok assert_equal nil,hash1[:two] #ok hash2 = Hash.new("dos") hash2[:one] = 1 assert_equal 1,hash2[
我从 RubyKoans开始经历about_hashes.rb.1练习让我感到困惑:
def test_default_value
    hash1 = Hash.new
    hash1[:one] = 1

    assert_equal 1,hash1[:one] #ok
    assert_equal nil,hash1[:two] #ok

    hash2 = Hash.new("dos")
    hash2[:one] = 1

    assert_equal 1,hash2[:one] #ok
    assert_equal "dos",hash2[:two] #hm?
  end

我的猜测是Hash.new(“dos”)使“dos”成为所有不存在键的默认答案.我对吗?

解决方法

是的,你是对的,看起来ruby公司有一个错误,hash2 [:two]将返回“dos”

看一下Hash.new方法文档

new → new_hash
new(obj) → new_hash
new {|hash,key| block } → new_hash

Returns a new,empty hash. If this hash is subsequently accessed by a
key that doesn’t correspond to a hash entry,the value returned
depends on the style of new used to create the hash. In the first
form,the access returns nil. If obj is specified,this single object
will be used for all default values
. If a block is specified,it will
be called with the hash object and the key,and should return the
default value. It is the block’s responsibility to store the value in
the hash if required.

旁注:在这种情况下,您可以通过运行实际代码或在irb或pry中执行几行来确认您的期望(我建议使用pry).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读