0

There are plenty of answers that allow us to achieve this like so:

array = [a: 1, b: 2, c: 3]. But what I'm looking for is something more closer to c++ or java implementation.

In C++ we can define an array of pairs like so:

map <pair<int,int>,int> mp;

and perhaps use it for assigning values like:

mp[{x1,y1}] = 1;

Or to check if some element exist like so:

while(range(x,y) && !mp[{x,y}]) {
    x += xx;
    y += yy;
    ans++;
 }

Now the question is, how can we define our array of hashes similar to c++ where we have something like:

 array = [{1,1}: 1, {2,2}: 2, {3,3}: 3]
4
  • Your last line says what you want, but it's not clear what you are given to produce that. Is it a = [1,2,3]? Please edit to clarify. Commented Oct 27, 2018 at 18:41
  • yes @CarySwoveland Commented Oct 27, 2018 at 18:43
  • 2
    {1,1} is not a valid Ruby object. Do you mean the array[1,1]? Commented Oct 27, 2018 at 18:46
  • yeh sorry, I'll update my code Commented Oct 27, 2018 at 18:57

2 Answers 2

3
a = [1, 2, 3]

a.map { |e| { [e,e] => e } }
  #=> [{[1, 1]=>1}, {[2, 2]=>2}, {[3, 3]=>3}]
Sign up to request clarification or add additional context in comments.

Comments

2

In Ruby maps are called Hashes. A Hash is a dictionary-like collection of unique keys and their values. The key of the hash can be of any type: number, symbol, string, array, other hash, etc.

So you could write it as a hash, where keys are arrays:

hash = {[1, 1] => 1, [2, 2] => 2, [3, 3] => 3}
# => {[1, 1]=>1, [2, 2]=>2, [3, 3]=>3} 

hash[[2, 2]]
# => 2

hash[[12, 34]] = 55
# => 55 

hash
# => {[1, 1]=>1, [2, 2]=>2, [3, 3]=>3, [12, 34]=>55} 

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.