1

I have a huge array

huge = 1000
huge_array = (1..huge).to_a

How to best "expand" this array so that each element becomes a sub-array of format [original_element, "default value"], preferably in a memory-friendly way (without an explicit #map loop?)

expanded_huge_array = huge_array.some_magic
#=> [[1, "default value"],[2, "default value"], ... [1000, "default value"]]
5
  • What does map have to do with it? If you need an array filled with values then you need an array filled with values. Why have the array index (plus one) be in the array at all? Etc. Commented Dec 7, 2015 at 15:40
  • Always assume the question is a watered down, easy-to-ask and easy-to-answer version of a non-trivial problem. The actual "huge_array" people may have will contain anything but an index. Commented Dec 8, 2015 at 7:30
  • No, assume the question is complete, and provides enough information to answer it in the most reasonable way possible. If there are hidden criteria then it's difficult to reason about, and answers may not suit what your'e actually asking. Commented Dec 8, 2015 at 11:50
  • Good point about hidden criteria. However, I rarely miss a chance to slightly over-interpret a question to provide a better learning and problem-solving opportunity. Commented Dec 8, 2015 at 12:18
  • Right--and without actual context, you can't provide a better learning and problem-solving opportunity, because you don't know what's really being asked. You introduced criteria without any explanation (e.g., why no map? Both map and zip make new arrays, but in different ways. Both iterate over the original array, the zip answer creates a new array of the huge array's size then iterates, etc) Commented Dec 8, 2015 at 12:37

2 Answers 2

2
huge_array.zip(['default value'] * huge_array.size)

BTW, you might simulate this behaviour with Hash with default:

arr = Hash.new { |h, key| huge_array.include?(key) ? [key, 'default value'] : nil }
arr[1]
#⇒ [1, 'default value']
arr[10000]
#⇒ nil
Sign up to request clarification or add additional context in comments.

2 Comments

Looks like #zip is the precision tool for this. Plus points for hash-with-block idea. (I wonder, what happens if such a hash is returned to a context where huge_array is not defined.)
No surprises, as the hash is called on an undefined key, the “local variable is not defined error” is raised.
1

Try Array#product:

Returns an array of all combinations of elements from all arrays.

>> [1,2,3].product(["a"])
=> [[1, "a"], [2, "a"], [3, "a"]]

1 Comment

> without an explicit #map loop?

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.