Ruby - Getting Value of Hash

Ruby - getting value of hash

Convert the key from a string to a symbol, and do a lookup in the hash.

hash = {:key1 => "value1", :key2 => "value2"}
k = 'key1'

hash[k.to_sym] # or iow, hash[:key1], which will return "value1"

Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases. I know that you've only tagged your question with Ruby, but you could steal the implementation of this class from Rails' source to avoid string to symbol and symbol to string conversions throughout your codebase. It makes the value accessible by using a symbol or a string as a key.

hash = HashWithIndifferentAccess.new({:key1 => "value1", :key2 => "value2"})
hash[:key1] # "value1"
hash['key1'] # "value1"

How to get a value from inside a hash in ruby on rails

Looks like you have a hash of hashes, where the key for the hash value is a unique string. However, you are not concern with the keys, so simply look through each hash value and treat this as the hash you want to retrieve from.

output.each do |key, value|
puts value['organization_id']
end

The difference here between your code and mine, is that without two outputs for this enumerator block, the value cta is only the hash keys.

Get a value from an array of hashes in ruby

The select statement will return all the hashes with the key 13.

If you already know which hash has the key then the below code will give u the answer.

ary[1][13]

However if you are not sure which of your hashes in the array has the value, then you could do the following:

values = ary.map{|h| h[13]}.compact

Values will have the value of key 13 from all the hashes which has the key 13.

get the values of a hash as integer instead of string in rails

You could parse each value as a JSON:

h.transform_values { |value| JSON.parse(value) }
# => {"1"=>[2, 44], "3"=>[50], "4"=>[43, 42], "9"=>[48, 40, 45, 41]}

Ruby: how can I retrieve a value in a hash knowing its (array) path?

Hash.dig accepts variable number of arguments, to convert array into "variable arguments" you need to use * (splat operator)

parentNode.dig(*path)

How to get values from hash for only specific keys stored in array

Hash#dig made its debut quite recently, in Ruby v2.3. If you need to support earlier versions of Ruby you can use Enumerable#reduce (aka inject).

def burrow(h, a)
a.reduce(h) { |g,k| g && g[k] }
end

h = {"2222"=>{"1111"=>"1"}, "2223"=>{"1113"=>"2"}, "12342"=>{"22343"=>"3"}}

burrow(h, ['2223','1113']) #=> "2"
burrow(h, ['2223']) #=> {"1113"=>"2"}
burrow(h, ['2223','cat']) #=> nil
burrow(h, ['cat','1113']) #=> nil

This works because if, for some element k in a, the hash given by the block variable g (the "memo") does not have a key k, g[k] #=> nil, so nil becomes the value of the memo g and will remain nil for all subsequent values of a that are passed to the block. This is how digging was normally done when I was a kid.

To change a value in place we can do the following.

def burrow_and_update(h, a, v)
*arr, last = a
f = arr.reduce(h) { |g,k| g && g[k] }
return nil unless f.is_a?(Hash) && f.key?(last)
f[last] = v
end

burrow_and_update(h, ['2223','1113'], :cat) #=> :cat
h #=> {"2222"=>{"1111"=>"1"}, "2223"=>{"1113"=>:cat}, "12342"=>{"22343"=>"3"}}

h = {"2222"=>{"1111"=>"1"}, "2223"=>{"1113"=>"2"}, "12342"=>{"22343"=>"3"}} # reset h
burrow_and_update(h, ['2223', :dog], :cat)
#=> nil

In the second case nil is returned because {"1113"=>"2"} does not have a key :dog.

Ruby/Rails return hash element if hash value is a string

What you need here is a recursion, i.e. a function, calling itself:

def filter_hash(hash)
hash.each_with_object({}) do |(key, value), acc|
acc[key] = value if value.is_a?(String)
acc[key] = filter_hash(value) if value.is_a?(Hash)
end
end

This function checks if the value of your hash is String, then it saves it, if it's a Hash it calls itself with that nested Hash

How to extract value from hash in Rails

@value_hash is not a hash, it's an ActiveRecord::Relation (as the error states).

In your example, @value_hash has only one member. To get that member, which is an instance of the class CustomValue (which is still not a hash!), you can do:

custom_value = @value_hash.first

Then, to get the year, you can do:

custom_value.year

Or, you could do it in one shot as:

@value_hash.first.year

Which is just a long way of saying exactly what Sachin R said (so you should accept their answer).

i have a large hash and i want to get specific values in ruby

You are trying to do too much all at once with hash_json['days'][0]['hours'][0]['datetime]. I suggest breaking this into smaller pieces. For example do days = hash_json['days']. Now you have a variable with simpler structure. In this case it is a list. You can get the first element with days[0] or loop over the list with days.each or days.map. I suggest you read about each and map to learn what they are good for and how they work.



Related Topics



Leave a reply



Submit