1

I have an array:

sheets # => [{"id"=>3, "subject"=>"www", "body"=>"www", "target_groups"=>"www", 0=>3, 1=>"www", 2=>"www", 3=>"www"}]

I am trying to call a certain element inside this array. I tried the following:

puts sheets[2] # => nil
puts sheets["subject"] # =>  `[]': can't convert String into Integer (TypeError)
puts sheets["subject.to_i"] # => `[]': can't convert String into Integer (TypeError) also.

Help would be appreciated.

1 Answer 1

4

The hash object is inside an array.

You need to fetch the hash object first (sheets[0]), then you can use key to fetch the item you want:

sheets = [{"id"=>3, "subject"=>"www", "body"=>"www",
          "target_groups"=>"www", 0=>3, 1=>"www", 2=>"www", 3=>"www"}]
sheets[0]["subject"]
# => "www"
Sign up to request clarification or add additional context in comments.

6 Comments

@falsetru generally in hashes the key/values doesn't store in memory in the sequence we specified,so if we specify sheets[0] then it will written id
@khan, sheets is not a hash, but an array of hashes: sheets = [...]
k so in that case sheets[1]["subject"]should return www and can u let me know how to access the multiple hashes i mean sheets[0][''] sheets[1][""]
@khan, Do you want something like this? sheets.map { |sheet| sheet['subject'] }
@falsetru Here is my data [{"Item_No"=>"7", "Update_Date"=>Wed Jun 03 "User _ID"=>"SAM-5555", "CREATE_DATE"=>Tue May 26 , "ID"=>"5555", " CRT_USER_ID"=>"SAM-5555"}] hash in an array,as u said earlier I tried item [0]["Item_No"] which returns "7" and also i wanted the value of next hash so I did item[2]["ID"] I got the following error "undefined method `[]' for nil:NilClass", what I am actually trying to do is to capture the retrieved data in single variable and assert it with the test data or any other suggestion regarding it will be usefull. Thanks
|

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.