Rails beginner
Rails beginner

Reputation: 14504

How do I iterate across a list of hashes?

I have an hash like this:

@json = [{"id"=> 1, "username" => "Example"}, {"id"=> 2, "username" => "Example 2"}]

I want to do something like this:

<ul>
    <% @json.each do |user| %>
    <li><%= user.username %></li>
    <% end %>
</ul>

and it would output a list with the two usernames.

Just tried this in IRB:

json2 = [{"id"=> 1, "username" => "Example"}, {"id"=> 2, "username" => "Example 2"}]
irb(main):076:0> json2.each do |user|
irb(main):077:1* user["id"]
irb(main):078:1> end
=> [{"id"=>1, "username"=>"Example"}, {"id"=>2, "username"=>"Example 2"}]
irb(main):079:0>

Upvotes: 2

Views: 195

Answers (4)

Ali Hassan Mirza
Ali Hassan Mirza

Reputation: 582

If you want to iterate hash which is in array you can use any of this.

@json = [{"id"=> 1, "username" => "user_name"}, {"id"=> 2, "username" => "user_name"}, {"id"=> 3, "username" => "user_name"}]

@json.each{|json| puts json['username'] } 

@json.collect{|json| json['username'] } 

@json.map{|json| json['username'] } 

If you want in the view then you can use

<ul>
  <% @json.each do |user| %>
    <li><%= user["username"] %></li>
  <% end %>
</ul>

Upvotes: 0

sufinsha
sufinsha

Reputation: 765

If you need output in console, then you need to do as follows:

@json = [{"id"=> 1, "username" => "Example"}, {"id"=> 2, "username" => "Example 2"}]
@json.collect{|json| puts json['username'] }

Upvotes: 2

Ameen
Ameen

Reputation: 84

json2 = [{"id"=> 1, "username" => "Example"}, {"id"=> 2, "username" => "Example 2"}]
json2.each do |user|
    puts user['username']
end

Upvotes: 2

Matheus Moreira
Matheus Moreira

Reputation: 17020

What you have there is a Hash, not a User object. Therefore, you must access the username using the index operator ([]):

<ul>

<% @json.each do |user| %>
  <li><%= user["username"] %></li>
<% end %>

</ul>

Upvotes: 2

Related Questions