0
arr = [
  {
    :id=>2,
    :start=> "3:30",
    break: 30,
    num_attendees: 14
  },
  {
    id: 3,
    start: "3: 40",
    break: 40,
    num_attendees: 4
  },
  {
    id: 4,
    start: "4: 40",
    break: 10,
    num_attendees: 40
  }
]

When I do the following

arr.map do |hash|
 [ hash[:id], hash[:start] ]
end

returns

#=> [[2, "3:30"], [3, "3: 40"], [4, "4: 40"]]

Is there an elegant and efficient way of passing an array like return_keys = [:id, :start] and get the same above values rather than hard coding inside the array.map

2 Answers 2

1

Would you consider the following elegant and efficient?

arr.map { |h| h.values_at(:id, :start) }
#=> [[2, "3:30"], [3, "3: 40"], [4, "4: 40"]]

or

arr.map { |h| h.values_at(*return_keys) }
#=> [[2, "3:30"], [3, "3: 40"], [4, "4: 40"]]
Sign up to request clarification or add additional context in comments.

1 Comment

It is elegant for sure but I have not benchmarking with anything else. So Thank you!
1

I find the following really expressive

keys = [:id, :start]
arr.map {|hash| hash.slice(*keys).values}

The slice method returns a hash only with the keys passed as parameters (which are preceded by the * operator to convert an array into keyword arguments and avoid hardcoding). Then, the values method gets just the values out of the hash

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.