3

I have some code in a view script that iterates through an array of arrays:

<% @rows.each do |data| %>
  <%= data[0] %>: <%= data[1] %><br>
<% end %>

How can I easily convert each data array to a hash so that I can refer to each item with a key?

<%= data[:name] %>: <%= data[:email] %><br>
4

3 回答 3

4

您可以像这样引用具有命名值的数组:

<% @rows.each do |name,email| %>
  <%= name %>: <%= email %><br />
<% end %>

这假定@rows数组的每个成员都是预期的二值数组。

于 2012-10-18T16:36:33.840 回答
2

@Zach 的回答还可以,但是严格按照您的要求回答,可以这样做:

@rows2 = @rows.map { |row| Hash[[:name, :email].zip(row)] }
于 2012-10-18T16:43:38.253 回答
2

@Zach 和 @tokland 提供了两个很好的答案。有时,最好制作一流的数据对象,而不是依赖原始哈希和数组的组合。 Struct对此很方便:

irb> EmailTuple = Struct.new :name, :email
=> EmailTuple
irb> rows = [%w{foo foo@example.com}, %w{bar bar@example.com}]
=> [["foo", "foo@example.com"], ["bar", "bar@example.com"]]
irb> rows2 = rows.map{ |row| EmailTuple[ *row ] }
=> [#<struct EmailTuple name="foo", email="foo@example.com">, #<struct EmailTuple name="bar", email="bar@example.com">]
irb> rows2.map{ |tuple| "#{tuple.name} has email #{tuple.email}" }
=> ["foo has email foo@example.com", "bar has email bar@example.com"]
于 2012-10-18T23:44:39.477 回答