2

I am collecting a response from a web service in a Rails' app with

response = #api.sql_data 

This causes response to equal the following.

response #=> { "success"=>true, "totalcount"=>10, "rows"=>[ # { "ID"=>"0001", "CODE"=>"0000001", "CODE_1"=>"Alpha", # "NAME"=>"Alpha", "Balance"=>"0" }, # { "ID"=>"0002", "CODE"=>"0000002", "CODE_1"=>"Beta", # "NAME"=>"Beta", "Balance"=>"0" }, # { "ID"=>"0003", "CODE"=>"0000003", "CODE_1"=>"Charlie", # "NAME"=>"Charlie", "Balance"=>"0"}, # ... # ] # } 

I have created the following method:

def format_response(response) response['rows'].map do |row| { id: row[0], code: row[1], code1: row[2], balance: row[4] } end.uniq { |x| x[:code1] } end 

When I execute this method for the above value of response, I obtain the following.

format_response(response) #=> [{:id=>nil, :code=>nil, :code1=>nil, :balance=>nil}] 

This is incorrect. I would like this expression to return the following.

{"ID"=>"0001", "CODE"=>"0000001", "CODE_1"=>"Alpha", "NAME"=>"Alpha", "Balance"=>"0"} 

What is my mistake?

1
  • HaCos, I trust my edit did not change your question. If it did please accept my apology and either edit my edit or roll-back to your original question. (Click "edited" to bring up the rollback option.) Commented Apr 12, 2017 at 3:01

2 Answers 2

3

response['rows'] contains an array of hashes. Hashes in ruby are not associative arrays so you cannot get the first key by hash[0].

def format_response(response) response['rows'].map do |row| { id: row["ID"], code: row["CODE"], code_1: row["CODE_1"], balance: row["BALANCE"] } end.uniq { |x| x[:code1] } end 
Sign up to request clarification or add additional context in comments.

Comments

3

Each row is a hash so you need to access its elements by name not by index (as you would with an array). The following should work:

def format_response(response) formatted_response = response['rows'].map do |row| { id: row['ID'], code: row['CODE'], code1: row['CODE_1'], balance: row['balance'] } end formatted_response.uniq { |x| x[:code1] } end 

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.