2

我有一个这样的哈希:

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

我想做这样的事情:

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

它会输出一个包含两个用户名的列表。

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

4 回答 4

2

你所拥有的是一个Hash,而不是一个User对象。因此,您必须使用索引运算符 ( []) 访问用户名:

<ul>

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

</ul>
于 2013-01-16T02:58:27.157 回答
2
json2 = [{"id"=> 1, "username" => "Example"}, {"id"=> 2, "username" => "Example 2"}]
json2.each do |user|
    puts user['username']
end
于 2013-01-16T07:54:30.813 回答
2

如果您需要在控制台中输出,那么您需要执行以下操作:

@json = [{"id"=> 1, "username" => "Example"}, {"id"=> 2, "username" => "Example 2"}]
@json.collect{|json| puts json['username'] }
于 2013-01-16T08:39:14.930 回答
0

如果你想迭代数组中的哈希,你可以使用其中的任何一个。

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

如果你想在视图中,那么你可以使用

<ul>
  <% @json.each do |user| %>
    <li><%= user["username"] %></li>
  <% end %>
</ul>
于 2015-09-19T09:35:50.923 回答