-1

Couldn't find a less confusing title but here is the pseudo-code:

for all video['tags'][i] in video['tags'][3..-1]
  topic = video['tags'][i]
  topic_array += video['id']
end

Let's say there are 2 elements in the video['tags'][3..-1]:

video['tags'][3..-1] # => ["Health", "Politics"]
video['id']          # => 35

I want to add the integer 35 to two different arrays named Health and Politics. Those arrays may or may not exist beforehand.

End result example:

Health # => [21, 25, 35]
Politics # => [35]
Emre
  • 81
  • 8

1 Answers1

1

Instead of using multiple arrays to store ids for each tag, i would use one hash in which each key is a tag and its value is the array of ids, for example:

tags = { "Health" => [21, 25] }

With that in place, you could solve your problem with something like this:

video["tags"][3..-1].each do |tag|
  tags.key?(tag) ? tags[tag] << video["id"] : tags[tag] = [video["id"]]
end

Check for tags contents:

tags
#=> {"Health"=>[21, 25, 35], "Politics"=>[35]}

To get the ids, you simply fetch/read the key (i.e tag) you want from tags hash, for example:

tags["Health"]
#=> [21, 25, 35]
Gerry
  • 10,337
  • 3
  • 31
  • 40
  • Thanks, but is my pseudo-code not realizable in Ruby? – Emre Jul 04 '17 at 14:14
  • @Emre You can use a `for` loop (check [this post](https://stackoverflow.com/questions/2032875/syntax-for-a-for-loop-in-ruby)), although its more idiomatic to use `each`; but you can't dynamically create variables, that's why another data structure (i.e `Hash`) is recommended. – Gerry Jul 04 '17 at 15:06