user7621056
user7621056

Reputation:

Creating new array using Hash key and values in Ruby

I have this question:

Given the family of hash members, with keys as the title and an array of names as the values, use the Ruby’s built in method to gather immediate family members (“brothers” and “sisters”) only into a new array.

With this hash:

family = {
  uncles:["bob", "joe", "steve"],
  sisters: ["jane", "jill", "beth"],
  brothers: ["frank", "rob", "david"],
  aunts: ["mary", "sally", "susan"]
}

How do I do this? I'm not even sure what built-in method I need to use. I'm a complete beginner in Ruby by the ways.

I have this:

new_family = Array.new
new_family = family.values_at(:brothers, :sisters)
p new_family

Which gives me:

[["frank", "rob", "david"], ["jane", "jill", "beth"]]

But I'm not sure if I'm doing this correctly? I feel like I might not fully be understanding the question?

Upvotes: 1

Views: 75

Answers (2)

Gerry
Gerry

Reputation: 10507

Here's another one:

new_family = [:brothers, :sisters].flat_map(&family.method(:[]))
#=> ["frank", "rob", "david", "jane", "jill", "beth"]

Upvotes: 1

treiff
treiff

Reputation: 1306

There are many different ways you could do this, you could simply do something like:

new_family = family[:brothers] + family[:sisters]

Or, like you have above:

new_family = family.values_at(:brothers, :sisters).flatten

Upvotes: 3

Related Questions