Ruby - TypeError: no implicit conversion of Hash into String Ruby - TypeError: no implicit conversion of Hash into String json json

Ruby - TypeError: no implicit conversion of Hash into String


The error is a result of calling Array#to_sentence on a hash.

Here's a fixed-up version with comments denoting the changes:

require 'json'text = "Hello world"json = '{"fruits": [{"name": "Apple", "location": "Harbor"}, {"name": "Banana", "location": "Kitchen"}, {"name": "Mango", "location": "Bedroom"}]}'fruits = JSON.parse(json)['fruits'] # append ['fruits']def format_fruits(fruits)  fruits.map do |fruit| # change each -> map    "\n\n#{ fruit['name'] }, #{ fruit['location'] }" # delete puts, [0]  end.join # change to_sentence -> joinendtext += format_fruits(fruits)puts text

Output:

Hello worldApple, HarborBanana, KitchenMango, Bedroom


In-case your json always contains "fruits" key, you can achieve this quite easily. Here:

fruits = JSON.parse(json)#=> {"fruits"=>[{"name"=>"Apple", "location"=>"Harbor"}, {"name"=>"Banana", "location"=>"Kitchen"}, {"name"=>"Mango", "location"=>"Bedroom"}]}fruits["fruits"].each { |hash|  puts "\n\n#{hash['name']}, #{hash['location']}"}

Another way to do this without using fruits key:

fruits.values.first.each { |hash|  puts "\n\n#{hash['name']}, #{hash['location']}"}