簡體   English   中英

如何在哈希數組中搜索包含某個鍵值對的哈希名稱? (紅寶石)

[英]How to search an array of hashes for the name of the hash containing a certain key-value pair? (Ruby)

我有這樣的事情:

array = [
  hash1 = {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
  hash2 = {"darco"=>"johnson", "girth"=>"wide", "onion"=>false},
  hash3 = {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

在任何給定時間只有一個oniontrue

我想要一個表達式或函數返回變量名稱(即hash1hash2 ),該變量包含onion當前為true的哈希。 我怎樣才能做到這一點?

這是不可能的。 一個對象不知道引用它的變量。

通過用hash替換數組並創建:hash1:hash2:hash3鍵,可以實現類似的效果。

假設我們有hash變量:

hash.keys.select{|key| hash[key]['onion']}

但是,如果您放寬要求,可以使用冒號:而不是=符號:

array = [
  hash1: {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
  hash2: {"darco"=>"johnson", "girth"=>"wide", "onion"=>false},
  hash3: {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

我們可以使用:

-> *_, **p { p.find { |_, v| v["onion"] }.first }.( *array )

好的,正如您在@JörgW Mittag發表的帖子的評論部分中所問的那樣- 是否有一種方法可以從洋蔥為真的數組中的哈希中返回某個鍵(但是不是洋蔥的鍵)? 是的,如下所示,這是可能的:

在這里,我考慮了一個輸入數組,其中存在多個Hash ,這些Hash對於鍵洋蔥具有true價值。 現在要處理這種情況,將需要enum#find_all

array = [
  {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
 {"darco"=>"johnson", "girth"=>"wide", "onion"=>true},
  {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

array.find_all{|i| i["onion"]== true}.map{|i| i.keys[0]}
#>>["marco", "darco"]

根據OP的輸入數組, enum#find可以工作。

array = [
  {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
 {"darco"=>"johnson", "girth"=>"wide", "onion"=>false},
  {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

array.find{|i| i["onion"] }.keys[0]
# => "marco"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM