Looping through an array and adding that data with a new key to hashes in a separate array

I am currently working on an app that scrapes data from mlb.com and the data is saved in arrays. I then want to iterate over the array of data and add each element to a hash. Here is a vanilla example of what I am attempting to do...

players = []

names = ["Kyle Freeland", "Jon Gray", "DJ Johnson"]

names.each do |name|
  players << {:name => name}
end

players 
=> [{:name=>"Kyle Freeland"}, {:name=>"Jon Gray"}, {:name=>"DJ 
Johnson"}]

So far this is exactly what I want but I also have a separate array storing each players' number that I am trying to push into each hash with a key of "number"...

numbers = ["21", "55", "63"]

I've been trying to do this by...

numbers.each do |number|
  players.each do |player|
    player[:number] = number
  end
end

Which ultimately gives me...

players
[{:name=>"Kyle Freeland", :number=>"63"}, {:name=>"Jon Gray", 
:number=>"63"}, {:name=>"DJ Johnson", :number=>"63"}]

So the final number is being pushed into each hash. Is there an easier way anybody can think of to push the correct numbers where they need to be? All data I am scraping will be in order.

Is this what you are looking for?

names = ["Kyle Freeland", "Jon Gray", "DJ Johnson"]
numbers = ["21", "55", "63"]

names.zip(numbers).map { |name, number| {name: name, number: number } }

Arrays and hashes in Ruby - DEV, Arrays and hashes are data structures that allow you to store multiple values at once. To add a new key-value pair to a hash, you can use the bracket notation as follows: You can loop through arrays and hashes by using the each method. For the hash, you separate the key and the value by a comma. For each key in my hash, I would like to loop through each element of the array, assign that to a scalar variable so that I can process it, then move onto the next element of the array. Once I have processed all the elements of the array for a key, I want to onto the next key and individually process all of the elements of its array, and so on.

names = ["Kyle Freeland", "Jon Gray", "DJ Johnson"]
numbers = ["21", "55", "63"]

players = names.zip(numbers).map { |x| { name: x[0], number: x[1] } }
#=> [{:name=>"Kyle Freeland", :number=>"21"}, {:name=>"Jon Gray", :number=>"55"}, {:name=>"DJ Johnson", :number=>"63"}]

names.zip(numbers) basically merges elements of self with corresponding elements from each argument resulting in [["Kyle Freeland", "21"], ["Jon Gray", "55"], ["DJ Johnson", "63"]].

Then we are iterating on this array and making relevant hashes.

Looping JavaScript Arrays Using for, forEach & More , There are different ways to loop over arrays in JavaScript, but it can be also arrays, which makes for a clean solution to index values by a key or name. Modern JavaScript has added a forEach method to the native array object. Each time an update was published the updated page data was added to� Perl array foreach FAQ: How do I loop over every element in a Perl array with a for loop (or foreach loop)?. A friend recently asked how to create a simple array of numbers with Perl, and also how to iterate over that list of numbers in a Perl foreach loop.

Your design has some weaknesses. You have two arrays containing information on players, with the ith element of each array pertaining to the same player. Presumably, if you wanted to add additional information for each player, such as batting averages, you would create an array of the same length as the first two that contained batting averages, being careful to keep them in the correct order. (I say "his" because at the present time all MLB players are men.)

That model is prone to error. Also, what will you do when you want to add data for additional players?

The first thing you need is a unique identifier for each player. For simplicity, let's assume that's his name, recognising that in a real application we would need to address the possibility of two players having the same name.1 Whenever you collect each datum it needs to be associated with the player's identifying characteristic, which we are assuming is his name, so we don't have to worry about the order of elements in arrays. For example, let's make our database an initially-empty hash, players, the keys being the players names and the values being a hash containing information for that player.

players = {}

Now suppose we want to add three players and their numbers to the hash:

numbers = {
  "Kyle Freeland"=>{ "number"=>"21" }, 
  "Jon Gray"     =>{ "number"=>"55" },
  "DJ Johnson"   =>{ "number"=>"63" }
}

We can then do the following:

def add_data(players, data)
  data.each do |player, datum|
    players[player] = {} unless players.key?(player)
    players[player].update(data[player])
  end
end

add_data(players, numbers)
players
  #=> {"Kyle Freeland"=>{"number"=>"21"},
  #    "Jon Gray"=>{"number"=>"55"},
  #    "DJ Johnson"=>{"number"=>"63"}}

The first thing that add_data does is to see if the hash players has a key player (e.g, "Kyle Freeland"). If it does not it adds that key to players and sets it value to an empty hash. Next it merges the value of player, datum, with the value of player in players. See the doc Hash#update, which is the same as Hash#merge!.

Now suppose we wanted to add data for a new player, add batting averages for these three players and correct Jon Gray's number, which should be "56":

batting_average = {
  "Kyle Freeland"=>{ "avg"=>302 }, 
  "Jon Gray"     =>{ "avg"=>246 },
  "DJ Johnson"   =>{ "avg"=>280 }
}

new_player = {
  "Dusty Rhodes" =>{"number"=>"12", "avg"=>312 }
}

correction = {
  "Jon Gray"=>{ "number"=>"56" }
}

add_data(players, batting_average)
add_data(players, new_player)
add_data(players, correction)

players
  #=> {"Kyle Freeland"=>{"number"=>"21", "avg"=>302},
  #    "Jon Gray"     =>{"number"=>"56", "avg"=>246},
  #    "DJ Johnson"   =>{"number"=>"63", "avg"=>280},
  #    "Dusty Rhodes" =>{"number"=>"12", "avg"=>312}} 

I don't mean to suggest that this is what you should do, merely that it is one of many designs you could employ that make the data analysis more reliable and easier to use than your present approach. In fact, if this were the real world you would undoubtedly want to use an SQL database for this application.

Incidentally, all your fields are strings. That's of course not necessary. I've entered batting averages as integers, which would facilitate calculations such as determining a players average batting average over, say, five years. (Perhaps floats, such as 0.302, would be even better). Also, try using symbols for keys (e.g., :avg=>312, which you can alternatively write avg: 312). As well as saving keystrokes there are other advantages which I won't get into now. In general, use symbols for keys as much as possible.

1. In 1934, for example, the Cubs had a second baseman named Zaphod Beeblebrox and the Yankees had an outfielder with the same name.

Arrays and Hashes, Learn about arrays and hashes, including how to iterate over these data We can add to a hash two ways: if we created it using literal notation, we can simply add a new key-value pair We could use a whole bunch of different methods f… With the security groups in a Array, you can iterate through the array items using a ForEach loop. A ForEach loop will allow you to add the users into each security group in the Array.

Here is a short example on how to solve this problem:

players = []

names = ["Kyle Freeland", "Jon Gray", "DJ Johnson"]
numbers = ["21", "55", "63"]

names.each_with_index do |name, idx|
  players << {:name => name, number: numbers[idx]}
end

How to loop through an associative array and get the key in PHP , Associative Array: Associative arrays are used to store key-value pairs. marks of the different subject of a student in an array, a numerically indexed array Program: Program to loop through associative array and print keys. PHP program to add item at the beginning of associative array � How to access� This component is rendered using ReactDOM on the DOM element with Id of root. Step 4 — Reformatting Array Objects.map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in

I hope this will help you.

names = ["Kyle Freeland", "Jon Gray", "DJ Johnson"]
numbers = ["21", "55", "63"]
names.zip(numbers).to_h

Iterate associative array using foreach loop in PHP, Both arrays can combine into a single array using a foreach loop. variable thereby saving the effort of creating a different variable for every data. list of elements of similar types, which can be accessed by using their index or key. PHP program to add item at the beginning of associative array � How to� How to display all items or values in an array using loop in jQuery. Topic: JavaScript / jQuery Prev|Next. Answer: Use the jQuery.each() function. The jQuery.each() or $.each() can be used to seamlessly iterate over any collection, whether it is an object or an

Ruby Hashes - A Detailed Guide, Hash methods. We also cover how to iterate over a hash and how to compare Array vs Hash in Ruby. Most commonly, a hash is created using symbols as keys and any data types as values. The older syntax comes with a => sign to separate the key and the value. Let's say you wanted to add on to an existing hash. Returns a new array consisting of key-value pairs from hash for which the block returns true. 32: hash.shift. Removes a key-value pair from hash, returning it as a two-element array. 33: hash.size. Returns the size or length of hash as an integer. 34: hash.sort. Converts hash to a two-dimensional array containing arrays of key-value pairs, then

Nested Arrays, Hashes & Loops in Ruby, Arrays and hashes are common data types used to store information. The main difference array. If we want to iterate through the inner elements, we have to add an inner loop: The output for the above code is quite different: [["hellotest" Accessing keys and values in a nested hash works the same way. When you run this code, you’ll be given a warning that a key should be provided for list items. A “key” is a special string attribute you need to include when creating lists of elements. We’ll discuss why it’s important in the next section. Let’s assign a key to our list items inside numbers.map() and fix the missing key issue.

Hash Iteration | Ruby Loops, In Ruby Collections, we learned about arrays and hashes. Hashes have several different ways of iteration -- keys, values, and both keys and values at the same�

Comments
  • Read the question once again please.
  • Its a Sample Method to avoid Looping.
  • yours is not providing the answer. it has to be{:name=>"Kyle Freeland", :number=>"21"}
  • players = names.zip(numbers).map { |x| { name: x[0], number: x[1] } } this will give the same. In ruby avoid looping its will increase your performance.
  • If performance is the real concerns, then Ruby should not be your language. Perhaps language like Rust should be your language