2

I am new to ruby and its nuances but I am running into this issue that I dont quite know how to fix or understand:

If I create the hash:

test = JSON.parse('[
    {"values":[
        ["header 1", "header 2", "header 3"],
        ["value 1", "value 2", "value 3"]]
    }]
')

Then I access test.values[0] I get:

[[["header 1", "header 2", "header 3"], ["value 1", "value 2", "value 3"]]]

As you can see it adds an extra layer onto the array. where what I would expect it to return would be:

[["header 1", "header 2", "header 3"], ["value 1", "value 2", "value 3"]]

Can anyone explain this to me or help mitigate this issue?

thanks!

4
  • 2
    you shouldn't be calling .values on an array (which is what test is) Commented Oct 12, 2016 at 20:43
  • 2
    You should be getting a syntax error for undefined method. Commented Oct 12, 2016 at 20:50
  • Thank you to the people who responded to this post. It definitely is that values is a method, and the unintended consequences from that was that it didn't go in and grab the key then get the contents but instead called the method values. Commented Oct 12, 2016 at 21:15
  • It absolutely doesn't when I run that code in Ruby 2.3.1. Maybe you have some library added on that's adding that method, but it's non-standard. Are you using Hashie or something else that extends Hash? If you are that would be test[0].values not what you put there. Commented Oct 12, 2016 at 21:53

2 Answers 2

4

I'm fairly certain that you aren't accessing the data in the right way as this:

test = JSON.parse('[
    {"values":[
        ["header 1", "header 2", "header 3"],
        ["value 1", "value 2", "value 3"]]
    }]
')

puts test[0]['values'].inspect
puts test[0]['values'][0].inspect

outputs:

[["header 1", "header 2", "header 3"], ["value 1", "value 2", "value 3"]] ["header 1", "header 2", "header 3"]

Sign up to request clarification or add additional context in comments.

Comments

1

Your JSON contains a key called values. In order to receive values from the hash try using it like this test[0]['values']. When using test[0].values you are actually calling Hash#values (instance method of Hash class) which returns all the values of every single key in your hash combined into the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.