簡體   English   中英

Ruby數組查找哈希值

[英]Ruby array to look up hash values

我還是這個新手,所以請耐心等待。 我有一個子字符串數組和一個包含子字符串和字符串的哈希。

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

例如,哈希值可能是"ount"=>"country" 我想通過從數組中提取"ount" ,然后輸出"country"作為"ount"鍵的值來查找它。 我想對數組中的每個子字符串執行此操作。

每個子字符串只有一個字符串。 這兩個列表都是按字母順序排列的,因此找到后停止並移至下一個是可以的。 我可以找到項目的數量,但寧願作為迭代來做,因此它是可重用的代碼(如果有道理的話)。

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

如果要在子字符串中打印每個元素的值

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"

如果要打印給定特定子字符串的值

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