arrays - 如何检查哈希键是否与数组中的值匹配
问题描述
我有:
arr = ['test', 'testing', 'test123']
ht = {"test": "abc", "water": "wet", "testing": "fun"}
如何选择ht
键匹配的值arr
?
ht_new = ht.select {|hashes| arr.include? hashes}
ht_new # => "{"test": "abc", "testing": "fun"}"
此外,我们如何从以下位置返回值:
arr = ["abc", "123"]
ht = [{"key": "abc", "value": "test"}, {"key": "123", "value": "money"}, {"key": "doremi", "value": "rain"}}]
output # => [{"key": "abc", "value": "test"}, {"key": "123", "value": "money"}]
解决方案
只需要稍作改动:
ht.select { |k,_| arr.include? k.to_s }
##=> {:test=>"abc", :testing=>"fun"}
请参阅哈希#select。
块变量_
(一个有效的局部变量),它是 key 的值k
,向读者表明它没有用于块计算。有些人更喜欢写那个|k,_v|
,或类似的。
推荐阅读
- assembly - Sjasm:无法组装 DW 或 OUTPUT 指令?
- python - 如何命名堆叠条形图中的每个条形标签?
- laravel - Laravel livewire 将 .csv 文件更改为 .txt,如何解决?
- javascript - 基于使用 jQuery 的单选按钮的禁用按钮条件
- javascript - ckeditor 无法在 db ajax 和 codiginoter 中更新数据
- laravel - laravel 旧版本不支持 php 8.0.8
- python - discord py bot中的多任务
- javascript - froala wysisyg 编辑器中字体大小的自定义文本输入
- flutter - 我应该什么时候覆盖 Flutter 中的 debugFillProperties?
- javascript - 有局部变量时如何使其无点?