将HASH转换为ARRAY

时间:2010-06-26 14:44:09

标签: ruby-on-rails ruby

将一些值保存到数据库后,我就是 发现难以打印出来。虽然我能够 从数据库中提取数据,输出如下:

@vars={:object=>"46789620999001", :source_id=>1, :comment=>"["This is 
my first commenttoday and tommorrow", "This is my first commenttoday 
and tommorrow", "This is my first commenttoday and tommorrow", "This 
is my first commenttoday and tommorrow", "This is my first comment", 
"This is my first comment", "its nice!!!", "Many people do not take 
this serious. In this life we have a big role to play in making 
ourselves what we would be. It is only God that can help us to live 
that life which we have planned, so we can only pray to Him who is the 
all and all in our life to help 
us."]", :title=>"", :content=>"<div>Life is beautiful. In this life, 
whatever you see is what you will use to make out your way. People 
around you can help you in many things and ways but can never live 
your life for you. It is left for you to live your life, make and take 
decisions that you think will help you in living out your dream life. 
I believe everybody has a dream life he would like to live. Whatever 
decisions one take today will go a long way in determining the kind of 
life the one will live in future.<br />Take this as an advise.Bye </ 
div><div class="blogger-post-footer"><img width='1' height='1' 
src='https://blogger.googleusercontent.com/tracker/ 
6876835757625487750-2447909010390406819?l=godwinagada.blogspot.com' 
alt='' /></div>", :author=>"["Godwin", 
"ken"]", :category=>"Reality", :post_id=>"", :date=>"2010-06-04", :FileName=>"first"} 
>] 

请有人帮忙参考本文中的每个数据 输出例如。

@output.each { |g| 
puts g.FileName 
puts g.post_id 
} 

3 个答案:

答案 0 :(得分:2)

你不想要:

@vars[:FileName]
@vars[:post_id]

答案 1 :(得分:0)

你有一个哈希,它包含一组键,每个键都指向一个值。有几种方法可以解决它们:

  1. 如果您只是想查看它来调试它。加载漂亮的打印(需要'pp')和漂亮的打印(pp @vars)。更棒的选择是Awesome Print gem。
  2. 如果输出每对的值,只需在每次传递一个块时进行迭代即可:
    @vars.each do |key, value|
      puts "#{key} => #{value}
    end

答案 2 :(得分:0)

从标准库中试用pp。

require 'pp'
pp @vars

还有另一个名为awesome_print的替代方案,您可以从http://rubygems.org/gems/awesome_print获取看起来像这样的宝石

require 'rubygems'
require 'ap'
ap @vars

其中任何一个都应该以更易于阅读的格式打印哈希值。