0

I have this array:

[["RESULT", "1"], ["RESPMSG", "User authentication failed"]] 

I want to access the RESPMSG element of the array and print its value, which can change, but its name is constant.

Any idea how I can print the array element by name? I tried like this, but I miss something:

decoded = URI::decode_www_form(@response_body, enc=Encoding::UTF_8) respmsg = decoded.index("RESPMSG") puts respmsg 

The main problem is that RESPMSG is not always at the position 1 in the array, otherwise would be easier.

2
  • 1
    To clarify, could you be wanting to use a Hash instead? If you're trying to print out the value of "RESULT" as 1 then a Hash is almost definitely what you're looking for. If this is the case, let me know and I'll leave an answer. Commented Oct 5, 2015 at 18:26
  • Yes, I thought about hash, all I need to do is to access the value of the "RESULT" element. Commented Oct 5, 2015 at 18:28

1 Answer 1

4

You can use a hash structure to access the value for "RESPMSG"

respmsg = Hash[decoded]["RESPMSG"] 
Sign up to request clarification or add additional context in comments.

3 Comments

It would be good to explain why a Hash would be the better choice over an Array. Also, using Hash[...] is somewhat deprecated in Ruby v2+ since Array now has to_h
@theTinMan Hash::[] is definitely not depreciated and I would dare to say it is preferable on something like SO where you cannot guarantee the OP's or any particular visitor's Ruby version. Due to its compatibility I would highly recommend this syntax since it is supported across all versions and I doubt it will reach depreciation status any time soon.
"is somewhat deprecated". The italics are significant. I agree, backwards compatibility is important, but for new code running on current Ruby it's a non-issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.