TAGS :Viewed: 8 - Published at: a few seconds ago

[ ruby - how can I access an variable ]

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).

Answer 1


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

Answer 2


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

Answer 3


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