繁体   English   中英

使用新的 Ruby 模式匹配来检查 hash 是否具有某些键

[英]Using new Ruby pattern matching to check if a hash has certain keys

我想在这个非常简单的案例中使用新的 Ruby 3 功能。 我知道这一定是可能的,但我还没有从文档中弄清楚。

给定一个 hash,我想检查它是否有某些键。 我不介意它是否还有其他人。 而且我想通过模式匹配来做到这一点(或者知道这是不可能的。)我也不想使用看起来过大的 case 语句。

{name: "John", salary: 12000, email: "john@email.com" } 
  1. 如果 hash 没有名称,并且 email 作为字符串,而工资作为数字,则会引发错误。

  2. 在 if 或其他条件中使用结构?

  3. 如果 hash 有字符串作为键(这是我从 JSON.parse 得到的)怎么办?

    {"name" => "John", "salary" => 12000, "email" => "john@email.com" }

“我也不想使用一个看起来矫枉过正的案例陈述。” case只是模式匹配的语法。 AFAIK 它与case when不同,它是 中的case in

h = {name: "John", salary: 12000, email: "john@email.com", other_stuff: [1] } 
case h
  in {name: String, salary: Integer, email: String}
    puts "matched"
  else
    raise "#{h} not matched"
end

您正在寻找=>运算符:

h = {name: "John", salary: 12000, email: "john@email.com" }
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键,但其值的 class 不应匹配:

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运算符返回 boolean 值而不是引发异常:

h = {name: "John", salary: 12000, email: "john@email.com" }
h in {name: String, salary: Numeric, email: String} # => true
h[:name] = 1
h in {name: String, salary: Numeric, email: String} # => false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM