简体   繁体   English

Ruby数组查找哈希值

[英]Ruby array to look up hash values

I'm still new to this, so bear with me. 我还是这个新手,所以请耐心等待。 I have an array of substrings and a hash that holds substrings and strings. 我有一个子字符串数组和一个包含子字符串和字符串的哈希。

substrings = ["sub1", "sub2", "sub3",...etc.]
hash = {"sub1"=>"string1", "sub2"=>"string2", "sub3"=>"string3"...}

For example, a hash value might be "ount"=>"country" . 例如,哈希值可能是"ount"=>"country" And I'd like to look it up by pulling "ount" from my array, and then outputting "country" as the value of the "ount" key. 我想通过从数组中提取"ount" ,然后输出"country"作为"ount"键的值来查找它。 I want to do this for every substring in the array. 我想对数组中的每个子字符串执行此操作。

Each substring has exactly one string. 每个子字符串只有一个字符串。 Both lists are alphabetical, so stopping when it's found and moving to the next is okay. 这两个列表都是按字母顺序排列的,因此找到后停止并移至下一个是可以的。 I can find a count of the items, but would rather do it as an iteration so it's reusable code, if that makes sense. 我可以找到项目的数量,但宁愿作为迭代来做,因此它是可重用的代码(如果有道理的话)。

substrings = ["sub1", "sub2", "sub3"]
hash = {"sub1"=>"string1", "sub2"=>"string2", "sub3"=>"string3"}

if you want to print value of each element in substrings 如果要在子字符串中打印每个元素的值

substrings.each do |str|
    p "value of #{str} is #{hash[str]}"  if hash.has_key?(str)
end

#output
"value of sub1 is string1"
"value of sub2 is string2"
"value of sub3 is string3"

if you want to print value for specific given substrings 如果要打印给定特定子字符串的值

def find_value(str,hash)    
    "value of #{str} is #{hash[str]}"  if hash.has_key?(str)
end

p find_value("sub1",hash)

#Output
"value of sub1 is string1"

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

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