【发布时间】:2019-01-24 18:39:58
【问题描述】:
我有:
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_new = ht.select {|hashes| arr.include? hashes}代表什么?是你失败的尝试吗?或者您是否声称它返回{"test": "abc", "testing": "fun"},这是一个谎言,因为键值对与arr进行比较,此外,ht中的任何键都不匹配arr,除非您从字符串转换为符号? -
第二个
ht不是有效的 Ruby 表达式。你的第二个问题也不清楚。