1

I have two arrays:

  • array of school names
  • array of school slugs

Say the array of school names is: [name1, name2, name3] and of slug names are: [slug1, slug2, slug3].

In ruby, how would I make an array [[name1, slug1], [name2, slug2], [name3, slug3]].

My attempt at the matter is kind of javascript-ish:

<% var schoolSelect = [];
for (var i=0; i<@schools.length; i++)
    schoolSelect[i] = [@schools.pluck(:name)[i], @schools.pluck(:slug)[i]]; %>
3
  • That doesn't look like a ruby for. Commented Jun 30, 2016 at 19:44
  • Could be more like (0..2).each do |position| code and also an end Commented Jun 30, 2016 at 20:08
  • Like I said, it was just an attempt haha - made it as best as I could in javascript form... I learned quickly that people don't like it when you don't post code so I posted something. Commented Jun 30, 2016 at 20:10

3 Answers 3

7

You will be using Array#zip for it like:

names = %w(name1 name2 name3)
slugs = %w(slug1 slug2 slug3)

names.zip(slugs)
# [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]
Sign up to request clarification or add additional context in comments.

1 Comment

nice approach. remove the commas though
2

Suggest you consider a Hash for that data structure

schools = ["first", "second", "third"]
slugs = ["a", "b", "c"]
school_slugs = {}

(0..2).each do |position|
  school_slugs[schools[position]] = slugs[position]
end
# => 0..2
school_slugs
# => {"first" => "a", "second" => "b", "third" => "c"}

If you use Arup's approach you can also make that into a Hash, i.e.

[["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]].to_h

# => {"name1"=>"slug1", "name2"=>"slug2", "name3"=>"slug3"} 

1 Comment

May be you can use each_with_object({}) insted of predefining hash
0
names = %w(name1 name2 name3)
slugs = %w(slug1 slug2 slug3)

Whenever you have two arrays of the same size, as here,

names.zip(slugs)
  #=> [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]

and

[names, slugs].transpose
  #=> [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]

are interchangeable.

Comments

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.