【问题标题】:Printing array of hashes reults in a single column instead of a row in ruby打印散列数组会在 ruby​​ 中生成一列而不是一行
【发布时间】:2015-01-01 04:38:12
【问题描述】:

我想在单列中打印哈希数组,但我的输出是连续打印

products = {"name":"kumar","results":[{"class":"one","site":[{"english":"twenty"}, {"english":"fouty"},{"english":"three"}]}]}

CSV.open("product.csv", 'wb') do |f|
productHash = products
  if productHash.haskey("results")
    productHash["results"].each do |p|
      if p.haskey("site")
        p["site"].each do |s|
          f << s["english"]
        end
      else
         f << "English not found"
     end
   else
     f << "results not found"
 end

上面的程序打印出下面的样式

 twenty
 foutrty
 three

我希望将其打印为

 twenty   fourty   three

我还需要在每个结果散列末尾换行,因为我有多个散列

【问题讨论】:

    标签: ruby arrays file csv hash


    【解决方案1】:

    尝试f.prints 而不是&lt;&lt;

    以下输出 twenty fouty three 并且如果有多个哈希值,每个哈希值将位于不同的行,因为 f.print "\n"

    products = {"name"=>"kumar","results"=>[{"class"=>"one","site"=>[{"english"=>"twenty"}, {"english"=>"fouty"},
            {"english"=>"three"}]}]}
    
    File.open("product.csv", 'wb') do |f|
        productHash = products
        if productHash.has_key?("results")
            productHash["results"].each do |p|
                if p.has_key?("site")
                    p["site"].each do |s|
                        f.print "#{s["english"]} "
                    end
                    f.print "\n"
                else
                    f.print "English not found\n"
                end
            end
    
        else
                f.print "results not found\n"
        end
    end
    

    编辑: 哈哈,我差点回去添加有关打印标签的内容。将 f.print "#{s["english"]} " 更改为 f.print "#{s["english"]}\t"。它会在行尾留下一个额外的空格或制表符,但为了尽可能少地进行更改,我认为没关系。

    【讨论】:

    • 仍然没有在标签中打印
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2014-01-27
    • 2023-03-03
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多