2010-06-26 87 views
0

節省一些值數據庫後,我 發現很難把它們打印出來。雖然我已經能夠 拉出數據庫的數據,輸出是這樣的:轉換HASH到數組

@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 
} 

+1

什麼是您的數組的指數和值?我在這裏沒有看到任何陣列。 – 2010-06-26 16:12:22

回答

2

你不想:

+0

@Godwin這是正確的 - 你不想哈希轉換爲數組,你要學習如何使用哈希 – 2010-06-26 15:30:22

+0

戴夫嗨,好了,我的問題可能是錯誤的。那麼,我該如何使用它呢? – Godwin 2010-06-26 16:04:04

+0

在這種情況下,如果'@ output'是一個與@var類似結構的散列數組,您可以使用當前代碼,但使用'g [:FileName]'和'g [:post_id]'代替當前代碼在你的街區。 – 2010-06-26 16:14:04

0

你有一個散列,其中包含了一組與每個鍵指向一個值的鍵。有幾種方法可以處理它們:

  1. 如果您只想查看它進行調試。加載漂亮的印刷品(需要'pp')和漂亮的印刷品(pp @vars)。一個更好的選擇是Awesome Print gem。
  2. 如果輸出每對的價值,只是每過一個塊爲您的操作循環:
     
    @vars.each do |key, value| 
        puts "#{key} => #{value} 
    end
0

嘗試PP,標準庫中。

require 'pp' 
pp @vars 

還有另外一種選擇叫awesome_print,你可以從消旋的http://rubygems.org/gems/awesome_print寶石,將這個樣子

require 'rubygems' 
require 'ap' 
ap @vars 

這些要麼應該打印哈希的格式,更易於閱讀。