2017-09-11 39 views
0

在OpsWorks中,我試圖測試給定節點的主機名上的數字後綴,並提取該數字,如果它不是1.如果數字不是1 ,我有這樣的正則表達式匹配的數量:OpsWorks紅寶石返回零有效的正則表達式測試

/([\d]+)$­/ 

這是針對符合此模式的節點命名方案運行:

  • 節點1
  • 節點2
  • 節點3
  • 節點(N ...)

我已經驗證了這個工程使用Rubular:當我運行這對一個實例與OpsWorks http://rubular.com/r/Ei0kqjaxQn

然而,本場比賽返回nil,不管是什麼號碼主機名在最後。 OpsWorks代理版本是寫作時的最新版本(4023),使用廚師12.13.37。

這是菜譜試圖使用匹配的數字代碼:

short_app_name.to_s + node['hostname'][/([\d]+)$­/, 1].to_s + '.' + app['domains'].first 

運行失敗,錯誤類型no implicit conversion of nil into String。但是,在檢查節點的數字後綴時,針對該屬性的正則表達式可以在配方的早期工作。我應該使用不同的方法來提取節點的後綴?


編輯:app['domains'].first填充。如果與domain.com換出,該行仍然會失敗,並顯示相同的類型錯誤。

回答

1

當我複製你的正則表達式,並貼到我的終端測試,有在正則表達式結束的美元符號後的軟連字符,去除這使得工作的事情:

網站沒有顯示甚至當我複製它從我的終端,而是一個屏幕截圖顯示的問題:

enter image description here

這第二行(「IRB(主要):002:0」)就是我複製/從你的食譜貼代碼,字符爲"\xc2\xad"

+0

有趣。這不是在我的編輯器(VS代碼)中,但我會刪除表達式並重新輸入它。也許它通過一些副本偷偷溜進去。我馬上回來報告。 – TorpedoBench

+0

這確實是個問題!不知何故,一些無形的破折號已進入我的正則表達式搜索。這個角色是不是在設計的大部分地方顯示?如果不是,我可能會在VS Code GitHub中記錄一個錯誤... – TorpedoBench

+0

我不確定它是否由設計或偶然顯示,它甚至可能只是一個「不支持此字體」類型的交易。 –

1

從食譜代碼和錯誤消息來看,問題可能是app['domains']在運行過程中是一個空數組。所以你可能想驗證它的值是否正確。

+0

這似乎最有可能實際上會導致他們張貼的錯誤(因爲'nil.to_s'不會返回' 「」'),我的答案交易與他們詢問的其他問題有關「這場比賽返回nil'」,這也似乎是合法的,只是沒有造成錯誤 –

+0

我可以驗證'app ['domains']'是否已填充。如果我用'domain.com'替換它也會失敗。 – TorpedoBench

0

你的錯誤與正則表達式無關。 的問題是,當你嘗試以連接現有String

app['domains'].first 

這是該錯誤會提高,因爲即使你String#slice返回nil您呼叫to_s所以它是一個空StringString唯一的地方+ nil如果app['domains'].firstnil將會引發此錯誤。

擊穿

#short_app_name can be nil because of explicit #to_s 
short_app_name.to_s 
#### 
# assuming node is a Hash 
# node must have 'hostname' key 
# or NoMethodError: undefined method `[]' for nil:NilClass wil be raised 
# node['hostname'][/([\d]+)$­/, 1] can be nil because of explicit #to_s 
node['hostname'][/([\d]+)$­/, 1].to_s 
##### 
# assuming app is a Hash 
# app must contain 'domains' key and the value must respond to first 
# and the first value must be a String or be implicitly coercible (#to_str) or it will fail with 
# TypeError: no implicit conversion of ClassName into String 
# could explicitly coerce (#to_s) like you do previously 
app['domains'].first 

例子:

node = {"hostname" => 'nodable'} 
app = {"domains" => []} 
node['hostname'][/([\d]+)$­/, 1] 
#=> nil 
node['hostname'][/([\d]+)$­/, 1].to_s 
#=> "" 
app["domains"].first 
#=> nil 
node['hostname'][/([\d]+)$­/, 1].to_s + '.' + app["domains"].first 
#=> TypeError: no implicit conversion of nil into String 
node = {"hostname" => 'node2'} 
app = {"domains" => ['here.com']} 
node['hostname'][/([\d]+)$­/, 1].to_s + '.' + app["domains"].first 
#=> "2.here.com" 
+0

app ['domains']的'.first'是返回其中的第一個項目,因爲OpsWorks將它填充爲''domains「:[」domain1.com「,」domain2.com「]' – TorpedoBench

+0

@ TorpedoBench並不總是如此。有時它會返回一個空數組'']'或至少一個'#first'返回'nil'的數組。沒有其他部分的代碼會導致這個錯誤。 – engineersmnky

+0

似乎OpsWorks在該數組中始終有一個值,因爲最後一項始終是應用定義的短名稱,即使它沒有在網站的應用定義頁面中顯示。不過,你是正確的,因爲在數據包上使用的方法不正確時,會返回'[]'。在這種情況下,雖然,這個問題是一個隱藏的字符在正則表達式本身:) – TorpedoBench