I have an array that looks like this.
[{"EntryId"=>"2", "Field1"=>"National Life Group","DateCreated"=>"2010-07-30 11:00:14", "CreatedBy"=>"tristanoneil"},
{"EntryId"=>"3", "Field1"=>"Barton Golf Club", "DateCreated"=>"2010-07-30 11:11:20", "CreatedBy"=>"public"},
{"EntryId"=>"4", "Field1"=>"PP&D Brochure Distribution", "DateCreated"=>"2010-07-30 11:11:20", "CreatedBy"=>"public"},
{"EntryId"=>"5", "Field1"=>"Prime Renovation Group, DreamMaker Bath & Kitchen", "DateCreated"=>"2010-07-30 11:11:21", "CreatedBy"=>"public"}
]
How would I go about iterating through this array so I can specify which field I want to print out and get the value, so I could do something like.
puts EntryId.value
The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element. This element is the one in which the index position is the value passed in.
The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.
An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable.
The presence of curly braces and hashrockets (=>
) means that you are dealing with a Ruby Hash, not an Array.
Luckily, retrieving the value (the thing to the right of the hashrocket) associated with any one key (the thing to the left of the hashrocket) is a piece of cake with Hashes: all you have to do is use the []
operator.
entry = { "EntryId" => "2", "Field1" => "National Life Group", ... }
entry["EntryId"] # returns "2"
Here is the documentation for Hash: http://ruby-doc.org/core/classes/Hash.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With