I'm having trouble accessing data in a "each" statement in Ruby. I'm grabbing data from an SQL query,
mysql> select * from mantis_bug_relationship_table WHERE relationship_type = 2 AND destination_bug_id = 753;
+-----+---------------+--------------------+-------------------+
| id | source_bug_id | destination_bug_id | relationship_type |
+-----+---------------+--------------------+-------------------+
| 103 | 765 | 753 | 2 |
+-----+---------------+--------------------+-------------------+
Then I add each of the results to an array like so that have a relationship_type of 2,
parent_map = {}
current = 1
# for each loop is here that populates parent_map
parent_map[current] = { issues_map[relation.destination_bug_id] => issues_map[relation.source_bug_id] }
current += 1
# for each loop is here that populates parent_map
Then I try to read data from the parent_map as follows:
parent_map.each do |child, parent|
pp parent_map
print "child: #{child}\n"
print "parent: #{parent}\n"
print "---------------------------------------\n"
STDOUT.flush
end
This outputs as follows:
{1=>{753=>765}}
child: 1
parent: 753765
The output should be:
child: 753
parent: 765
How am I supposed to access the child and parent?
You are actually dealing with hashes in your example, not arrays.
array = []
hash = {}
In your parent_map.each
loop you are grabbing the key and value. Your key is populated by the current
variable in your initial population loop, while your value is also a hash containing the parent and child you want to access.
Assuming you want the hash that is your value, you need a sub loop, ala:
parent_map.each do |key, val| # This val is your hash: {753=>765}
val.each do |child, parent|
puts "child: #{child}" # 753
puts "parent: #{parent}" # 765
end
end
You do not need nested loops as in other answers. Take the second parameter and decompose it.
parent_map.each do |_, (child, parent)|
pp parent_map
puts "child: #{child}"
puts "parent: #{parent}"
puts "---------------------------------------"
STDOUT.flush
end
parent_map.each do |current, issues_hash|
issues_hash.each do |key, value|
print "child: #{key}\n"
print "parent: #{value}\n"
end
end
This should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.