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?

1
  • you don't need a method for that..they work as hash[:key] Commented May 12, 2017 at 11:12

2 Answers 2

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
%>
Sign up to request clarification or add additional context in comments.

1 Comment

Doing that just returns 50 when doing json['speed'] How do I print the string I want by passing the key?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.