Ruby with hash reading json response values

str = ’ “paging”][“next” ’
puts str => “paging”][“next”

hash[“paging”][“next”] => this is working fine
but hash[str] => this is not working

how to make it work?

Hi,

I’m not quite sure what you’re trying to do, so more code context may be required, I get an error when replicating what you have:

syntax error, unexpected ']', expecting end-of-input
puts str => "paging"]["next"

Here is how I create a hash “normally”:

require 'awesome_print'

hash = {}
hash["paging"] = "test"

ap hash
p hash["paging"]

if you wanted to go one further and create a hash from a json object, use “JSON.parse” (requires json) to convert from a string to a hash, for example:

require 'awesome_print'
require 'json'

my_json = '{"paging": "test"}'
my_hash = JSON.parse(my_json)
ap my_hash
p my_hash["paging"]

I hope that answered your question, if not, if you can clarify your scenario I can try and help further. My advice is to use awesome_print gem (gem install awesome_print) and use ‘ap’ to print the hash (or what you think is a hash) it will print it nicely for you:

lipsum = "lorem ipsum lorem dolor lorem ipsum sit dolor sit amet ipsum sit"

p word_count(lipsum)
# {"lorem"=>3, "ipsum"=>3, "dolor"=>2, "sit"=>3, "amet"=>1}


#==--------- my additional bonus notes ---------------------------------=#
# awesome_print to pretty=print a hash
require 'awesome_print'
# run 'gem install awesome_print' at a command prompt if missing.


ap word_count(lipsum)
# {
#     "lorem" => 3,
#     "ipsum" => 3,
#     "dolor" => 2,
#       "sit" => 3,
#      "amet" => 1
# }

Hope that helps!

str is a variable, not a macro that is expanded and parsed at compile time. When you say hash[str], it’s literally looking for a value in the top-level hash with key “paging”][“next”, and there is no such key.

Try:
path = %w(paging next);
hash.dig(*path)

If you’re using an older Ruby without #dig, use the XKeys gem instead.

There are methods that allow you to convert data into different types. .to_s will convert things into a string. Example

array = %w(‘hello world’)
puts array.to_s

You can also do a block form

hash.each_with_index do |key ,value|
puts key.to_s
puts value.to_s
end

In your example, you want hash.to_s instead of hash[str]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

Sponsor our Newsletter | Privacy Policy | Terms of Service