如何遍历散列列表?

时间:2022-11-22 21:38:44

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:

刚刚在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>

4 个解决方案

#1


2  

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>

#2


2  

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

#3


2  

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'] }

#4


0  

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>

#1


2  

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>

#2


2  

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

#3


2  

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'] }

#4


0  

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>