我想在這個非常簡單的案例中使用新的 Ruby 3 特性。我知道這一定是可能的,但我還沒有從檔案中弄清楚。
給定一個哈希,我想檢查它是否具有某些鍵。我不介意它是否還有其他人。而且我想通過模式匹配來做到這一點(或者知道這是不可能的。)我也不想使用看起來過大的 case 陳述句。
{name: "John", salary: 12000, email: "[email protected]" }
如果散列沒有名稱,電子郵件作為字串,薪水作為數字,則引發錯誤。
在 if 或其他條件中使用結構?
如果哈希有字串作為鍵(這是我從 JSON.parse 得到的)怎么辦?
{"name" => "John", "salary" => 12000, "email" => "[email protected]" }
uj5u.com熱心網友回復:
您正在尋找=>運營商:
h = {name: "John", salary: 12000, email: "[email protected]" }
h => {name: String, salary: Numeric, email: String} # => nil
再加上一對 ( test: 0):
h[:test] = 0
h => {name: String, salary: Numeric, email: String} # => nil
沒有:name鑰匙:
h.delete :name
h => {name: String, salary: Numeric, email: String} # key not found: :name (NoMatchingPatternKeyError)
使用:name鍵但其值的類不應匹配:
h[:name] = 1
h => {name: String, salary: Numeric, email: String} # String === 1 does not return true (NoMatchingPatternKeyError)
嚴格匹配:
h[:name] = "John"
h => {name: String, salary: Numeric, email: String} # => rest of {:test=>0} is not empty
運算子回傳一個布林值而in不是引發例外:
h = {name: "John", salary: 12000, email: "[email protected]" }
h in {name: String, salary: Numeric, email: String} # => true
h[:name] = 1
h in {name: String, salary: Numeric, email: String} # => false
uj5u.com熱心網友回復:
“我也不想使用一個看起來矯枉過正的案例陳述。” case只是模式匹配的語法。AFAIK 它與 a 不同case when,它是 a case in。
h = {name: "John", salary: 12000, email: "[email protected]", other_stuff: [1] }
case h
in {name: String, salary: Integer, email: String}
puts "matched"
else
raise "#{h} not matched"
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410174.html
標籤:
