简体   繁体   English

从ruby中的哈希写入CSV

[英]Write into CSV from a hash in ruby

I'm trying to write into a CSV some Hash elements. 我正在尝试将一些Hash元素写入CSV。 @boo_hoo is my hash for each of its keys, if they have a single value, I don't want them in the CSV. @boo_hoo是我每个键的哈希值,如果它们只有一个值,则我不希望它们出现在CSV中。 There must be something wrong with my syntax. 我的语法一定有问题。 Could someone please explain a bit how to access the key+values of a hash in this case? 在这种情况下,有人可以解释一下如何访问哈希的键值吗? Thanks! 谢谢!

CSV.open("final_data.csv", "wb") {|csv| 
    @boo_hoo.to_a.each.count {|k, v|
        count.v > 1 csv << |k, v|
    } 
}

Welcome to Stack Overflow. 欢迎使用堆栈溢出。 When you next write a post, you can use the code formatting tools to make it a bit easier to read. 下次编写帖子时,可以使用代码格式化工具使其更易于阅读。

I can see a few errors here. 我可以在这里看到一些错误。

  1. As per Mark's comment, count.v should be v.count . 根据Mark的评论, count.v应该是v.count
  2. You've combined two statements on one line with no separator, so I'd guess your error message is like unexpected tIDENTIFIER, expecting end-of-input . 您已经在没有分隔符的一行上合并了两个语句,所以我想您的错误消息就像unexpected tIDENTIFIER, expecting end-of-input You want to chain them together so that if your condition is met, then the args are added to the csv. 您希望将它们链接在一起,以便满足条件,然后将args添加到csv中。
  3. Vertical pipes |k, v| 垂直管|k, v| are used to denote block arguments in ruby, but you're repeating them when you probably want an array. 用于在ruby中表示块参数,但是当您可能需要数组时,您要重复它们。
  4. I don't really see what .to_a.each.count is doing for you, except possibly causing more syntax errors. 我真的看不到.to_a.each.count在为您做什么,除了可能导致更多语法错误。

To write this in one line: 要写成一行:

CSV.open("final_data.csv", "wb") {|csv| @boo_hoo.each {|k, v| csv << [k, v] if v.count > 1 } }

That might be a bit long, so I'd be tempted to break out the block into a multiline block: 这可能会有点长,所以我很想将代码块分成多行代码块:

CSV.open("final_data.csv", "wb") do |csv| 
  @boo_hoo.each {|k, v| csv << [k, v] if v.count > 1 } 
end

EDIT: You've edited your post as I wrote this. 编辑:我写这篇文章时,您已经编辑了您的帖子。 In ruby, it's an idiom to use single braces {} for a block consisting of a single line of code, but do ... end for a block that stretches over multiple lines. 在ruby中,对包含一行代码的代码块使用单括号{}是一个习惯用法,但是do ... end延伸到多行代码的代码块do ... end

Also, in response to Mudasobwa's comment, you probably want to add a splat operator [k,*v] . 另外,为了响应Mudasobwa的评论,您可能想要添加splat运算符[k,*v] My code is valid ruby, but the output probably isn't what you want. 我的代码是有效的ruby,但是输出可能不是您想要的。 Let's say @boo_hoo = {:a=>[1, 2, 3], :b=>[1], :c=>[1, 2]} . 假设@boo_hoo = {:a=>[1, 2, 3], :b=>[1], :c=>[1, 2]} The code above produces the output 上面的代码产生输出

a,"[1, 2, 3]"
c,"[1, 2]"

If you change the block to 如果将块更改为

@boo_hoo.each {|k, v| csv << [k, *v] if v.count > 1 }

you get the output 你得到的输出

a,1,2,3
c,1,2

which is almost certainly what you actually want in a CSV. 这几乎可以肯定是您实际想要的CSV格式。

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

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