Search code examples
jsonrubyruby-hash

Select specific key from hash in Ruby


I have the following JSON which I convert to hash:

<%
  json = '{
    "speed": 50,
    "braking": 50,
    "time_on_task": 50
  }'
  json = JSON.parse(json)
%>

And currently I just loop through them and display them:

<ul>
  <% json.each do |t| %>
      <li><%= "<b>#{t.first.humanize}</b>: #{t.last}".html_safe %></li>
  <% end %>
</ul>

However I'd like to build a method that can pick an particular item by its key name. e.g. show_score(json, 'speed')

I tried:

def show_score(hash, key)
  hash.select { |k| k == key }
end

Which just returns: {"speed"=>50}

So I tried:

hash.select { |k, h| "<b>#{k.humanize}</b>: #{h}".html_safe if k == key }

But it returns the same...

How can I get to just return the string in the format I want if they key matches?


Solution

  • def show_score(hash, key)
      "<b>#{key.humanize}</b>: #{hash[key]}"
    end
    

    And I'd change this

    <%
      json = '{
        "speed": 50,
        "braking": 50,
        "time_on_task": 50
      }'
      json = JSON.parse(json)
    %>
    

    into

    <%
      hash = {
        "speed" => 50,
        "braking" => 50,
        "time_on_task" => 50
      }
      json = hash.to_json
    %>