Return key by value 多值时

Return key by value when multiple values

这是一个散列:

cities = {
  OR: ['Bend','Portland'],
  CA: ['Los Angeles', 'Sandiego'],
  WA: ['Seattle', 'Vancouver'],
}

我正在 return 通过值的元素查找键。当我按城市名称(值中的元素)搜索时,我想 return 州的缩写(键)。

以下仅在 value 是散列值时才有效,而不是当它是值的元素时:

hash.key(value)

您可以使用select找到密钥:

hash.select { |k, v| v.include? "Seattle" }.keys.first