Ruby 2.0 中增加了将nil转成哈希对象的方法 nil.to_h

ruby2.0以前,像下面的方法 如果 hash 为nil 直接爆掉!

def test_nil_to_hash(hash)  hash["follow"]endtest_nil_to_hash({"follow" => "me"}) #=> "me"test_nil_to_hash(nil)  #=> undefined method `[]' for nil:NilClass (NoMethodError)

我们要避免抛出NoMethodError一般会这么写:

def test_nil_to_hash(hash)  (hash || {})["follow"]endtest_nil_to_hash(nil) #=>  nil

从 ruby2.0 开始增加了Nil#to_h方法, (hash || {}) 这种写法成为历史啦!

def test_nil_to_hash(hash)  hash.to_h["follow"]end
Ruby 2.0 中增加了将nil转成哈希对象的方法 nil.to_h

相关文章:

你感兴趣的文章:

标签云: