简体   繁体   中英

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" . 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. 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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