2014-09-19 44 views
2

我有此數組:紅寶石 - 我如何可以訪問一個變量

{ 
:details=> [ 
     { 
    "account"   =>"", 
    "address"   =>"", 
    "category"   =>"send", 
    "amount"   =>0.0, 
    "fee"   =>0.0 
    }, 
    { 
    "account"   =>"payment", 
    "address"   =>"SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU", 
    "category"   =>"receive", 
    "amount"   =>1.0 
    } 
] 
} 

我如何可以訪問紅寶石第二個「地址」元素?當我做

address: detail[:address] 

我只得到了第一個(裏面是空的)。

回答

2

怎麼樣:

data = { 
:details=> [ 
     { 
    "account"   =>"", 
    "address"   =>"", 
    "category"   =>"send", 
    "amount"   =>0.0, 
    "fee"   =>0.0 
    }, 
    { 
    "account"   =>"payment", 
    "address"   =>"SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU", 
    "category"   =>"receive", 
    "amount"   =>1.0 
    } 
] 
} 

然後(因爲,你永遠不知道Array內部哈希的序列):

data[:details].detect{|d| !d['address'].empty? }['address'] 
1

只是解決陣列

obj = { 
:details => [ 
    { 
    "account"   =>"", 
    "address"   =>"", 
    "category"  =>"send", 
    "amount"   =>0.0, 
    "fee"    =>0.0 
    }, 
    { 
    "account"   =>"payment", 
    "address"   =>"SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU", 
    "category"  =>"receive", 
    "amount"   =>1.0 
    } 
] 
} 

obj[:details][1]['address'] 

這裏的第二個元素是在線REPL:http://repl.it/ZZm

+0

這隻適用於下一個地址。 – Anthony 2014-09-19 17:38:28

+0

@安東尼你是什麼意思? – zavg 2014-09-19 17:39:00

+0

@Anthony在帖子作者問第二個「地址」,不是嗎? – zavg 2014-09-19 17:39:42

0

採用注射方法,你可以得到所有的人都像這樣:

[21] pry(main)> results = [] 
=> [] 
[22] pry(main)> json[:details].inject { |sum, k| results << k["address"] } 
=> [["SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU"]]