Home > Enterprise >  How to access values from a get request in a hash (ruby)
How to access values from a get request in a hash (ruby)

Time:03-12

Say I have a get request :

def get (var)
  uri = URI('url')
  res = Net::HTTP.get_response(uri)
  parse = JSON.parse(res[:body])
  {parse['color'] => parse ['id']}

The get requests takes a variables and returns a hash. I know in my slim file doing something like

get(var)['red']

would give me the corresponding value to the key 'red'. However what if I wanted to access the key/values of the hash by their names. So something like

get(var)['color']

Would something like that be possible? Say the response of the request was {'red' => 3} Can I access the key 'red' by calling 'color' like in the above code. I realise the syntax of the above code is most likely incorrect.

CodePudding user response:

The returned value of get is only a single element hash like {'red' => 3}

If you want to get the key and the value without accessing the entry using

get(var)['red']

=> 3

you could do the following:

get(var).keys.first

=> 'red'

get(var).values.first

=> 3

or you could take the return value and map it into a new hash:

new_hash = {"color" => get(var).keys.first, "id" =>get(var).values.first}

then access like this:

new_hash["color"]

=> red

new_hash["id"]

=> 3

  • Related