10

I have a JSON array that looks something like this.

[
 {"name":"Idaho","state":{"id":1,"name":"A"}},
 {"name":"Wyoming","state":{"id":1,"name":"A"}},
 {"name":"Montana","state":{"id":2,"name":"B"}},
 {"name":"South Dakota","state":{"id":1,"name":"B"}}
]

How would I use Ruby to only show the value of A?

I don't think sort_by will be the answer because what I have below just sorts them alphabetically. I want to completely exclude all results from B.

.sort_by { |a| [a.state.name] }

What would be the most efficient way to do this in a .rb file?


I solved my own question. This is how I achieved what I wanted.

.select { |a| a.state.name == "A" }
3
  • 1
    a.state.name is how you'd do it in JavaScript, but in Ruby this is a['state']['name']. Commented Sep 4, 2014 at 20:40
  • Also worth reading up on is the Enumerable#select method. Commented Sep 4, 2014 at 20:42
  • Alternatively, str.scan(/[A-Z][a-zA-Z\s]+(?=.+:\"A\".+?$)/) => ["Idaho", "Wyoming"]. Commented Sep 5, 2014 at 0:44

3 Answers 3

5
require 'json'

json = <<'JSON_STRING'
[
 {"name":"Idaho","state":{"id":1,"name":"A"}},
 {"name":"Wyoming","state":{"id":1,"name":"A"}},
 {"name":"Montana","state":{"id":2,"name":"B"}},
 {"name":"South Dakota","state":{"id":1,"name":"B"}}
]
JSON_STRING

data = JSON.parse json

data.map(&:values).select { |state, values| values["name"] == ?A }
#=> [["Idaho", {"id"=>1, "name"=>"A"}], ["Wyoming", {"id"=>1, "name"=>"A"}]]

data.map(&:values).select { |state, values| values["name"] == ?A }.map(&:first)
#=> ["Idaho", "Wyoming"]
Sign up to request clarification or add additional context in comments.

Comments

2
require 'json'

arr = JSON.parse <<END_OF_JSON
[
 {"name":"Idaho","state":{"id":1,"name":"A"}},
 {"name":"Wyoming","state":{"id":1,"name":"A"}},
 {"name":"Montana","state":{"id":2,"name":"B"}},
 {"name":"South Dakota","state":{"id":1,"name":"B"}}
]
END_OF_JSON

results = []

arr.each do |hash|
  results << hash["name"] if hash["state"]["name"] == "A"
end

p results

--output:--
["Idaho", "Wyoming"]

Comments

0

Incorrect:

.select { |a| a.state.name == "A" }

Correct way:

.select { |a| a['state']['name'] == 'A' }

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.