2

I have this array:

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

How can I access the second "address" element in ruby? When I do

address: detail[:address] 

I get only the first one (which is empty).

3 Answers 3

2

How about:

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

And then(Because, you never know the sequence of Hashes inside Array):

data[:details].detect{|d| !d['address'].empty? }['address'] 
Sign up to request clarification or add additional context in comments.

Comments

1

Just address the second element of array

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'] 

Here is online REPL: http://repl.it/ZZm

2 Comments

@Anthony what do you mean?
@Anthony in post author asked for second "address", isn't it?
0

Using the inject method you can get all of them like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.