我如何解析这个哈希数组?

时间:2013-10-04 00:31:14

标签: ruby-on-rails ruby arrays parsing hash

我有以下哈希数组,我需要解析所有非空的电子邮件:

[{:id=>"something", :first_name=>"First", :last_name=>"Name", :name=>"First Name", :email=>"first_name@gmail.com", :gender=>nil, :birthday=>nil, :profile_picture=>nil, :relation=>nil}, 
{...},
{}]

我试图这样做:

- @contacts[0].each_with_index do |c, i|
  - unless c[:email].blank?
    %tr
      %td= c[:email]
      %td= check_box_tag "email_to[]", c[:email], true

但我收到错误:

An ActionView::Template::Error occurred in users#parse_data:

  no implicit conversion of Symbol into Integer

如何正确做到?

3 个答案:

答案 0 :(得分:1)

在视图中进行大量处理并不是一件好事。有简单的条件和循环是可以理解的,但是在控制器中应该进行繁重的处理。

沿着这些方向使用:

ary = [
  {:id=>"something", :first_name=>"First", :last_name=>"Name", :name=>"First Name", :email=>"first_name@gmail.com", :gender=>nil, :birthday=>nil, :profile_picture=>nil, :relation=>nil}, 
  {:id=>"something", :first_name=>"First", :last_name=>"Name", :name=>"First Name", :email=>"", :gender=>nil, :birthday=>nil, :profile_picture=>nil, :relation=>nil}, 
  {}
]

viewable_email = ary.reject{ |e| e.empty? || e['email'].empty? }

此时viewable_email将仅包含要显示的哈希值。你的观点只能绕过它们。

答案 1 :(得分:0)

@contacts.each_with_index do |c, i| ...

答案 2 :(得分:0)

当您在哈希上说each_with_index时,您将获得如下所示的数组

{:id=>"something", :first_name=>"First", :last_name=>"Name"}.each_with_index{|e,i| p e}
[:id, "something"]
[:first_name, "First"]
[:last_name, "Name"]

所以,你不能说e[:id],这就是错误的原因。如上所述,@contacts[0]将为您提供哈希而不是数组。

相关问题