[英]Accessing entire hash in context inside block
說我有這個哈希:
hash = { :c => "three", :a => "one", :b => "two" }
我想在結尾處添加:
one, two, three
現在說這很好地嵌套在另一個哈希中。 我想避免這樣的事情:
puts "#{bigger_hash[0].hash[:a]}, #{bigger_hash[0].hash[:b]}, #{bigger_hash[0].hash[:c]}"
我知道有這種形式的map
,可以讓我做這樣的事情而無需定義順序:
bigger_hash[0].hash.map{|k,v| v}.join(', ')
將輸出:
three, one, two
這消除了靈活性。 我想按我想要的順序明確地解決這些問題(不一定是數字或字母!)
有什么便捷的方法可以實現? 我在考慮以下方面:
bigger_hash[0].hash.magic{"#{a}, #{b} #{c}"}
# or
bigger_hash[9].hash.magic(:a, :b, :c).join(', ')
也許這是你的ans:
bigger_hash[9].hash.values_at(:a, :b, :c).join(', ')
什么是bigger_hash
返回? 我不確定您要尋找的是什么,但據我了解,您想keys
對哈希進行排序並返回其values
。 檢查一下:
> hash = { :c => "three", :a => "one", :b => "two" }
> hash.sort.map{|e| e[1] }.join(' , ')
=> "one , two , three" # your expected output
要么
> hash.values_at(:a, :b, :c).join(', ')
=> "one, two, three"
您也可以使用以下類型:
hash = { :c => "three", :a => "one", :b => "two" }
Hash[hash.sort].values.join(", ")
# => "one, two, three"
但是在這種情況下,map方法更好。
首先,應該定義排序功能:
sorter = lambda { |o1, o2| o1 <=> o2 }
然后,您可以按需要對值進行排序:
hash = { :c => "three", :a => "one", :b => "two" }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ one, two, three
例如,對於逆序,我們得到:
sorter = lambda { |o1, o2| o2 <=> o1 }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ three, two, one
舊版紅寶石沒有#to_h
方法:
hash.sort(&sorter).map(&:last).join(', ')
就地分揀機:
hash.sort(&lambda{ |o1,o2| o1 <=> o2 }).map(&:last).join(', ')
#⇒ "one, two, three"
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.