With Ruby, if I have a hash, what is the fastest way to check if it has a key from an array of strings? So I could do this
使用Ruby,如果我有一个哈希,检查它是否有来自字符串数组的键的最快方法是什么?所以我能做到这一点
has_key = false
arr_of_strings.each do |str|
if my_hash.has_key?(str)
has_key = true
break
end
end
But taht seems like way too many lines of code for such a simple inquiry.
但对于如此简单的查询,似乎有太多代码行。
3 个解决方案
#1
1
strings = ['a', 'b', 'c']
hash = {:a => 'apple', :b => 'bob', :d => 'thing'}
has_key = hash.keys.map(&:to_s) & strings # ['a', 'b']
has_key.any? # true
a one-liner that's similar, hash.keys.detect { |key| strings.include?(key.to_s) }.nil?
一个类似的单行,hash.keys.detect {| key | strings.include?(key.to_s)} .nil?
#2
5
As simple as this:
就这么简单:
arr_of_strings.any? {|s| my_hash.key?(s) }
Or, to get bonus points for clever-yet-less-readable code:
或者,为巧妙但不易读的代码获得奖励积分:
arr_of_strings.any?(&my_hash.method(:key?)) # => true
#3
3
To see if the array and the keys have any in common, you can use set intersection:
要查看数组和键是否有任何共同点,可以使用set intersection:
(arr & hash.keys).any?
#1
1
strings = ['a', 'b', 'c']
hash = {:a => 'apple', :b => 'bob', :d => 'thing'}
has_key = hash.keys.map(&:to_s) & strings # ['a', 'b']
has_key.any? # true
a one-liner that's similar, hash.keys.detect { |key| strings.include?(key.to_s) }.nil?
一个类似的单行,hash.keys.detect {| key | strings.include?(key.to_s)} .nil?
#2
5
As simple as this:
就这么简单:
arr_of_strings.any? {|s| my_hash.key?(s) }
Or, to get bonus points for clever-yet-less-readable code:
或者,为巧妙但不易读的代码获得奖励积分:
arr_of_strings.any?(&my_hash.method(:key?)) # => true
#3
3
To see if the array and the keys have any in common, you can use set intersection:
要查看数组和键是否有任何共同点,可以使用set intersection:
(arr & hash.keys).any?