-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]

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but is my pseudo-code not realizable in Ruby?
@Emre You can use a for loop (check this post), 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.