-1

I have a hash returned to me in ruby

test_string = "{cat=6,bear=2,mouse=1,tiger=4}"

I need to get a list of these items in this form ordered by the number.

animals = [cat, tiger, bear, mouse]

My thoughts were to_s this in ruby and split on the '=' character. Then try to order them and put in a new list. Is there an easy way to do this in ruby? Sample code would be greatly appreciated.

joncodo
  • 2,298
  • 6
  • 38
  • 74
  • It's unclear what you're asking here. Do you have the data in your first code block as a Hash object, or as a string representing a hash object? – asthasr May 29 '13 at 17:06
  • a string representing a hash object. – joncodo May 29 '13 at 17:06
  • http://stackoverflow.com/questions/1667630/how-do-i-convert-a-string-object-into-a-hash-object perhaps that will help especially the answer about splitting? – Doon May 29 '13 at 17:12
  • You don't need to `to_s` it, it's already a string. – user229044 May 29 '13 at 17:13
  • He doesn't use the standard `Hash#to_s`representation though. No hashrockets. – tsm May 29 '13 at 17:13
  • That is the problem. I have only the '=' charter and it is sent to me from the client. I cant change it. I need to convert it to rockets – joncodo May 29 '13 at 17:15
  • I don't understand the question. Do you want a string `{cat=6,bear=2,mouse=1,tiger=4}` to be converted into `[cat, tiger, bear, mouse]` or an hash? – Shoe May 29 '13 at 17:16

5 Answers5

7
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)
fgb
  • 18,439
  • 2
  • 38
  • 52
1

Not the most elegant way to do it, but it works:

test_string.gsub(/[{}]/, "").split(",").map {|x| x.split("=")}.sort_by {|x| x[1].to_i}.reverse.map {|x| x[0].strip}

Siyu Song
  • 897
  • 6
  • 21
1
 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"]
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
1

The below code should do it. Explained the steps inline

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
Amey
  • 8,470
  • 9
  • 44
  • 63
0
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"]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317