Ruby 超好用的 Safe Navigation (安全讀取)

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
600   0  
·
2018/03/04
·
2 mins read


享受 Ruby 「&」 的一路順暢

Rails 就是 Ruby,Ruby 2.3 版以後,我想現在大家應該也都是使用這些版本了,有一個很好用的功能,就是 Safe Navigation,Safe Navigation 在中文的世界中,好像沒人翻譯過,事實上,連英文都很難猜懂,但是如果知道使用的方法與意義,就好懂多了。

Safe Navigation 幾乎在新的語言中都有,可以參考一下 Wiki,我覺得叫它“安全讀取”還不錯,為什麼呢?以在 Ruby/Rails 的常常使用環境中,有一個例子非常的棒的解釋了我為什麼說 Safe Navigation 叫它“安全讀取”還不錯:

在真實世界中,我們常要透過一個資料去讀另一個檔案的資料,這是在通常不過的使用,最直白的寫法就是(文章去找作者):

Article.find(23).user.name 

這樣如果去考試,一定會被刷掉,因為,Article可能沒有id=23的資料,所以就出現錯誤了,標準答案一般都是:

article = Article.find_by(id: 23)
if article.present?
  article.user.name
end

如果主考官很機車的話,還會被問為什麼不用其他方法?確實,還是有很多其他方法,但是都是好長啊⋯⋯

如果用 Safe Navigation(安全讀取)那就簡單多了,把以上改程式碼改成:

Article.find_by(id: 23)&.user.name 

這 & 運算元會阻擋 “nil” 通過,其他就會通過,所以以上的程式碼就是說,如果 article.find_by 有資料 (所以不是 nil )就繼續下一步,這樣就知道為什麼英文是叫 Safe Navigation 而我覺得叫它“安全讀取”還不錯了吧。 & 運算元不是萬能,它就是只能阻擋 “nil” 通過,記得這點就好,是個很好用的功能!


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
日期:
創作於:2018/03/04,最後更新於:2018/03/04。
合計:437字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.