## 12.安全導航
Ruby 努力成為程序員最好的朋友。 它的制造商正在發明新的方法來改善你的編碼體驗。 Ruby 2.3 中的此類改進之一是安全導航。 或者一種寫不會引發意外錯誤的條件的方法。 請參閱下面的程序,鍵入并執行
```rb
# safe_navigation.rb
class Robot
attr_accessor :name
end
robot = Robot.new
robot.name = "Zigor"
puts "The robots name is #{robot.name}" if robot&.name
```
輸出量
```rb
The robots name is Zigor
```
因此,程序可以完美地執行而不會出現故障。 查看代碼`if robot&.name`,我們很快就會了解它的重要性。
現在,讓我們來看一下機器人尚未初始化的情況。 那是 robot = Robot.new 未編寫,程序看起來如下圖所示
```rb
# safe_navigation_2.rb
robot = nil
puts "The robots name is #{robot.name}" if robot&.name
```
當我們執行上面的程序時,它仍然不會引發錯誤! 現在看代碼`if robot&.name`,它可以解決問題,我們將看看如何。 現在在下面鍵入程序并執行
```rb
# not_safe_navigation.rb
robot = nil
puts "The robots name is #{robot.name}" if robot.name
```
Output
```rb
not_safe_navigation.rb:4:in `<main>': undefined method `name' for nil:NilClass (NoMethodError)
```
因此,這引發了一個錯誤。 但是在這里,我們將`if`條件寫為`if robot.name`,我們還沒有使用安全導航。 現在我們知道了場景。 首先,我們必須檢查變量`robot`是否存在或不存在`nil`,如果`robot.name`也不為 nil,那么我們就不能打印該東西。 因此,要更正 [not_safe_navigation.rb](code/not_safe_navigation.rb) ,我們輸入以下代碼。
```rb
# not_safe_navigation_2.rb
robot = nil
puts "The robots name is #{robot.name}" if robot and robot.name
```
看一下我們需要如何使用 and 運算符提供長條件,如下所示:
```rb
if robot and robot.name
```
相反,我們可以簡單地寫成
```rb
if robot&.name
```
如 [safe_navigation.rb](code/safe_navigation.rb) 中所示,這很方便。
- 前言
- 紅寶石
- 先決條件
- 1.安裝 Ruby
- 2.在線資源
- 3.入門
- 4.比較與邏輯
- 5.循環
- 6.數組
- 7.哈希和符號
- 8.范圍
- 9.功能
- 10.可變范圍
- 11.類&對象
- 12.安全導航
- 13.打破大型程序
- 14.結構和 OpenStruct
- 15. Rdoc
- 16. Ruby 樣式指南
- 17.模塊和混入
- 18.日期和時間
- 19.文件
- 20. Proc,Lambda 和塊
- 21.多線程
- 22.異常處理
- 23.正則表達式
- 24.寶石
- 25.元編程
- 26.基準
- 27.測試驅動開發
- 28.觀察者模式
- 29.模板模式
- 30.工廠模式
- 31.裝飾圖案
- 32.適配器模式
- 33.單例模式
- 34.復合模式
- 35.建造者模式
- 36.策略模式
- 贊助商
- 捐
- 人們怎么說
- 版權
- 取得這本書