0

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?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Cameron
  • 27,963
  • 100
  • 281
  • 483

2 Answers2

3
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
%>
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • Doing that just returns `50` when doing `json['speed']` How do I print the string I want by passing the key? – Cameron May 12 '17 at 11:16
1

I think you're thinking too hard, or maybe I'm not understanding your question fully.

<ul>
  <% json.each do |k,v| %>
      <li><%= "<b>#{k.humanize}</b>: #{v}".html_safe %></li>
  <% end %>
</ul>

ps. using Enumerable#detect is so much faster than Enumerable#select.first

Josh Brody
  • 5,153
  • 1
  • 14
  • 25