Dr.Rabbit
Dr.Rabbit

Reputation: 129

Looping ruby hash and output specific element

I am trying to loop through a hash for specific data to output. If I want to output all usernames. This is how I can do it one at a time but its not what I want.

puts username = json["users"][0]["username"]
puts username = json["users"][1]["username"]

also tried

json.each { |x| puts json["users"][x]["username"]}

This is the hash structure

{"success"=>true, "users"=>[{"id"=>"1523493", "username"=>"myname","age"=>"21"},{"id"=>"653172", "username"=>"anothername","age"=>"65"}]}

sorry I didnt make my question clear enough. I am wanting to iterate the hash for "username" and then i can loop through each username and output specific data before moving to next username

Upvotes: 0

Views: 50

Answers (3)

Amit Badheka
Amit Badheka

Reputation: 2672

You can loop your json like this

json["users"].each do |u|
   username = u["username"]
   #Do some logic with username
   #like user = User.find_by_username(username)
end

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110685

h = {"success"=>true, 
     "users"=>[{"id"=>"1523493", "username"=>"myname","age"=>"21"},
               {"id"=>"653172", "username"=>"anothername","age"=>"65"}]}

h["users"].map { |user| user["username"] }
   #=> ["myname", "anothername"] 

Upvotes: 0

Zoran
Zoran

Reputation: 4226

You can get all the usernames in one go by doing something like this:

json = { "users" => [{"id"=>"1523493", "username"=>"myname"},{"id"=>"653172", "username"=>"anothername"}] }

json["users"].map { |user| user["username"] }
# => ["username", "anothername"]

The above will provide you with an array of usernames to do with as you see fit. :)

Hope it helps!

Upvotes: 1

Related Questions