Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby symbol as key, but can't get value from hash

Tags:

symbols

ruby

hash

I'm doing some update on other one's code and now I have a hash, it's like:

{"instance_id"=>"74563c459c457b2288568ec0a7779f62", "mem_quota"=>536870912, "disk_quota"=>2147483648, "mem_usage"=>59164.0, "cpu_usage"=>0.1, "disk_usage"=>6336512}

and I want to get the value by symbol as a key, for example: :mem_quota, but failed.

The code is like:

instance[:mem_usage].to_f

but it returns nothing. Is there any reason can cause this problem?

like image 342
Lory_yang Avatar asked Nov 28 '22 21:11

Lory_yang


2 Answers

Use instance["mem_usage"] instead since the hash is not using symbols.

like image 147
Conner Avatar answered Dec 19 '22 03:12

Conner


The other explanations are correct, but to give a broader background:

You are probably used to working within Rails where a very specific variant of Hash, called HashWithIndifferentAccess, is used for things like params. This particular class works like a standard ruby Hash, except when you access keys you are allowed to use either Symbols or Strings. The standard Ruby Hash, and generally speaking, Hash implementations in other languages, expect that to access an element, the key used for later access should be an object of the same class and value as the key used to store the object. HashWithIndifferentAccess is a Rails convenience class provided via the Active Support libraries. You are free to use them yourself, but they have first be brought in by requiring them.

HashWithIndifferentAccess just does the conversion for you at access time from string to symbol.

So, for your case, instance["mem_usage"].to_f should work.

like image 31
ebeland Avatar answered Dec 19 '22 03:12

ebeland