`
Hooopo
  • 浏览: 339076 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

the difference: Array[] and Array.fetch [via comp]

    博客分类:
  • Ruby
阅读更多
array = ["a","b","c"]        # => ["a", "b", "c"] 
array[1]                     # => "b" 
array.fetch 1                # => "b" 
# ================================================== # 
# So far, so fine. 
# ================================================== # 
array[666]                   # => nil 
array.fetch 666 
IndexError: index 666 out of array 
        from (irb):5:in `fetch' 
        from (irb):5 

This may seem like a trival difference between the two, but
I am wondering in general why they behave differently.
Or in other words, why array[] does not return an error
whereas .fetch specifically does.

You might say that's the purpose of fetch, to raise an exception for
out-of-bounds indexes when [] just returns nil. Pick the method you want
depending on the error handling you want.

fetch is more general; if you want it to behave like []() in this case,
say array.fetch(666,nil)

PS:也可以指定fetch返回其他值


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics