简体   繁体   English

Rails通过哈希循环

[英]Rails Loop Through Hash

A really simple question but I just can't seem to get it working. 一个非常简单的问题,但我似乎无法使其正常工作。

There is only one Property included below but there could be more than one within Properties . 以下仅包含一个Property ,但是Properties可以有多个。 How can I iterate through this hash and display just the Name of each Property ? 如何遍历此哈希并仅显示每个PropertyName

{"GetPropertiesResponse"=>{"Properties"=>{"Property"=>{"Breakfast"=>"IN", "Country"=>"GB", "Currency"=>"GBP", "Id"=>"1834", "Name"=>"Hotel Name"}}}}

I've tried this in my view: 我认为这是尝试过的:

<% @json['GetPropertiesResponse']['Properties']['Property'].each do |property| %>
  <%= property['Name'] %>
<% end %>

I'm getting this error: 我收到此错误:

no implicit conversion of String into Integer 没有将String隐式转换为Integer

If you are saying there might be more than one property hash then this should work: 如果您说的可能是一个以上的property哈希,那么这应该起作用:

<% @json['GetPropertiesResponse']['Properties'].each do |property, value| %>
  <%= value['Name'] %>
<% end %>

I would use #each_value on this hash since you don't appear to be using the keys 我会在此哈希上使用#each_value ,因为您似乎没有使用键

<% @json['GetPropertiesResponse']['Properties'].each_value do |value| %>
  <%= value['Name'] %>
<% end %>

Should work. 应该管用。 Note that the second line is <%= value['Name'] %> and not <%= property['Name'] %> 请注意,第二行是<%= value['Name'] %>不是 <%= property['Name'] %>

PS On a different note, I don't know why you're using the key "Property" inside of your Properties hash. 附注:换句话说,我不知道您为什么要在Properties哈希中使用键“ Property”。 That just seems like a good way to confuse yourself in exactly this way. 这似乎是一种以这种方式混淆自己的好方法。 Your keys within the Properties hash should be something unique to the property they describe. “属性”哈希中的键应该是它们描述的属性所独有的。 Since each will be a property, the string "Property" doesn't help describe or differentiate. 由于每个都是属性,因此字符串“ Property”无助于描述或区分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM