我有一個散列紅寶石拆分字符串在Ruby中
test_string = "{cat=6,bear=2,mouse=1,tiger=4}"
我需要這種形式的數量排序,這些項目的列表退還給我。
animals = [cat, tiger, bear, mouse]
我的想法是這個在紅寶石和'='字符分裂。然後嘗試訂購它們並放入新的列表中。有沒有簡單的方法來做到這一點在紅寶石?示例代碼將不勝感激。
我有一個散列紅寶石拆分字符串在Ruby中
test_string = "{cat=6,bear=2,mouse=1,tiger=4}"
我需要這種形式的數量排序,這些項目的列表退還給我。
animals = [cat, tiger, bear, mouse]
我的想法是這個在紅寶石和'='字符分裂。然後嘗試訂購它們並放入新的列表中。有沒有簡單的方法來做到這一點在紅寶石?示例代碼將不勝感激。
a = test_string.split('{')[1].split('}').first.split(',')
# => ["cat=6", "bear=2", "mouse=1", "tiger=4"]
a.map{|s| s.split('=')}.sort_by{|p| p[1].to_i}.reverse.map(&:first)
# => ["cat", "tiger", "bear", "mouse"]
不是最優雅的方式來做到這一點,但它的工作原理:
test_string.gsub(/[{}]/, "").split(",").map {|x| x.split("=")}.sort_by {|x| x[1].to_i}.reverse.map {|x| x[0].strip}
s = "{cat=6,bear=2,mouse=1,tiger=4}"
a = s.scan(/(\w+)=(\d+)/)
p a.sort_by { |x| x[1].to_i }.reverse.map(&:first)
下面的代碼應該這樣做。 解釋的步驟內聯
test_string.gsub!(/{|}/, "") # Remove the curly braces
array = test_string.split(",") # Split on comma
array1= []
array.each {|word|
array1<<word.split("=") # Create an array of arrays
}
h1 = Hash[*array1.flatten] # Convert Array into Hash
puts h1.keys.sort {|a, b| h1[b] <=> h1[a]} # Print keys of the hash based on sorted values
test_string = "{cat=6,bear=2,mouse=1,tiger=4}"
Hash[*test_string.scan(/\w+/)].sort_by{|k,v| v.to_i }.map(&:first).reverse
#=> ["cat", "tiger", "bear", "mouse"]
目前還不清楚你問這裏。你將第一個代碼塊中的數據作爲散列對象還是表示散列對象的字符串? – syrion
表示散列對象的字符串。 – joncodo
http://stackoverflow.com/questions/1667630/how-do-i-convert-a-string-object-into-a-hash-object也許這將有助於特別是關於分裂的答案? – Doon