Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Accessing Array Elements

Tags:

ruby

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
like image 933
Tristan O'Neil Avatar asked Oct 02 '10 13:10

Tristan O'Neil


People also ask

How do you access elements in an array Ruby?

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.

How do you iterate an array in Ruby?

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.

How does array work in Ruby?

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.


1 Answers

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

like image 132
Raphomet Avatar answered Sep 30 '22 17:09

Raphomet