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

rockliu · 2013年05月03日 · 最后由 Rei 回复于 2013年05月03日 · 3312 次阅读

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

def test_nil_to_hash(hash)
  hash["follow"]
end

test_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"]
end

test_nil_to_hash(nil) #=>  nil

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

def test_nil_to_hash(hash)
  hash.to_h["follow"]
end

Sounds Good

我一般这么写

UPDATE 这是错的

def test_nil_to_hash(hash = {})
  hash["follow"]
end

当然,nil 能 to_h 更完备了。

#2 楼 @Rei 这样传值是 nil 的时候好像不行吧

2.0 这样挺好的

然后兼容旧版本可以这样:

unless nil.respond_to?(:to_h)
  class NilClass
    def to_h
      {}
    end
  end
end

#3 楼 @goinaction 你对了,原来我一直写了个 bug。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号