下面的代碼應該是關于 OR 運算子的奇怪 Ruby 行為的一個很好的例子:
def search_by_name_active
if request.path == (name_search_registrants_path \
|| new_registrant_path)
'active'
end
end
和規格:
describe "#search_by_name_active" do
it "should return active if current page is new_registrant" do
allow(helper.request).to receive(:path).and_return(new_registrant_path)
expect(helper.search_by_name_active).to eq('active')
end
end
這給了我一個錯誤:
Failure/Error: expect(helper.search_by_name_active).to eq('active')
expected: "active"
got: nil
如果我洗掉括號:
def search_by_name_active
if request.path == name_search_registrants_path \
|| new_registrant_path
'active'
end
end
第一個規范將通過,但不是以下規范:
it "should return nil if current page is not search_by_name" do
allow(helper.request).to receive(:path).and_return(id_search_registrants_path)
expect(helper.search_by_name_active).to be_nil
end
Failure/Error: expect(helper.search_by_name_active).to be_nil
expected: nil
got: "active"
怎么回事?!除了像下面這樣的附加方法之外,還有其他方法可以寫出這個邏輯等式嗎?
def search_by_name_active
if request.path == name_search_registrants_path
'active'
elsif request.path == new_registrant_path
'active'
end
end
uj5u.com熱心網友回復:
這種行為在所有編程語言中都是預期的,而不僅僅是 ruby??。為了簡化您的示例:
x == (a || b)
...不等于:
(x == a) || (x == b)
第一個運算式在與 比較(a || b) 之前x進行評估。因此,您只比較x其中一個值,而不是兩個值。
用所有編程語言撰寫此代碼的通用方法是使用上面的第二個代碼示例。或者換句話說,使用您的具體示例:
if request.path == name_search_registrants_path \
|| request.path == new_registrant_path
或者,我們可以通過幾種特定于 ruby?? 的方法來縮短此代碼:
# Works in any ruby code
if [name_search_registrants_path, new_registrant_path].include?(request.path)
# Works in any rails code
if request.path.in? [name_search_registrants_path, new_registrant_path]
第二個示例是特定于 rails 的,因為它使用了對核心 ruby?? 語言的擴展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440700.html
下一篇:每n行追加一行到檔案-ruby
