1

I am not an expert of Ruby and I try to use elements from a string that was part of a big JSON message. I never been able to use JSON.parse for whatever reason but was able to find a way to loop over the object. But at the end, I have this remaining string that I don't know how to get the value:

{:time=>"2014-09-11 10:59:27 +0000", :cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}

This is attached to a variable called appUsage. If I try appUsage["cpu"] I obtained: cpu. I have tried couple looping suggestion from research on Internet but I just don't know enough Ruby - I guess - to know the right one that will works.

P.S.: For those who would like to know where this "string" is coming from, this is the result that coming from the app.stats from the library of CFoundry.

Stijn Bernards
  • 1,091
  • 11
  • 29
FYB
  • 19
  • 3
  • so you mean `appUsage = '{:time=>"2014-09-11 10:59:27 +0000", :cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}'` it's a string you are getting? – rony36 Sep 11 '14 at 11:35

2 Answers2

2

That's a ruby Hash (not a String) containing what it seems like a Date, Float and Fixnum objects

You were close trying appUsage["cpu"] but the keys in your Hash are symbols rather than string, meaining its :cpu not "cpu" and yes ruby Hash treats each as a different key.

app_usage = {:time=>"2014-09-11 10:59:27 +0000", :cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}

app_usage[:cpu]
# > 0.02421584874444766

app_usage[:disk]
# > 635125760

To convert your string to a hash to use it like written above use eval(). In your case, if you have a string called a you can turn your string to hash by calling eval(a), and then you can use your hash:

a = "{:cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}"
app_usage = eval(a)
app_usage[:cpu] # => 0.02421584874444766

But as stated in this answer:

It has severe security implications. It executes whatever it is passed, you must be 110% sure (as in, at least no user input anywhere along the way) it would contain only properly formed hashes or unexpected bugs/horrible creatures from outer space might start popping up.

Community
  • 1
  • 1
Nimir
  • 5,727
  • 1
  • 26
  • 34
  • 1
    Thank you for your great explication. So you made me learn the "hash" aspect of Ruby! ;-) – FYB Sep 11 '14 at 12:58
0

What I got from you question:

'{:time=>"2014-09-11 10:59:27 +0000", :cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}' is a string.

That means:

appUsage = '{:time=>"2014-09-11 10:59:27 +0000", :cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}'

So we have to convert this String object into Hash object. And there is a dirty way to do this. :p

appUsage = eval '{:time=>"2014-09-11 10:59:27 +0000", :cpu=>0.02421584874444766, :mem=>192069632, :disk=>635125760}'

For more details check this thread out.

Community
  • 1
  • 1
rony36
  • 3,277
  • 1
  • 30
  • 42