0

So, I need to add two arrays together to populate a third. EG

a = [1,2,3,4]
b = [3,4,5,6]

so that:

c = [4,6,8,10]

I read the answer given here: https://stackoverflow.com/questions/12584585/adding-two-ruby-arrays

but I'm using the codecademy labs ruby editor and it's not working there, plus the lengths of my arrays are ALWAYS going to be equal. Also, I don't have any idea what the method ".with_index" is or does and I don't understand why it's necessary to use ".to_i" when the value is already an integer.

It seems like this should be really simple?

2 Answers 2

3
a = [1,2,3,4]
b = [3,4,5,6]
a.zip(b).map { |i,j| i+j } # => [4, 6, 8, 10] 

Here

a.zip(b) # => [[1, 3], [2, 4], [3, 5], [4, 6]]

and map converts each 2-tuple to the sum of its elements.

Sign up to request clarification or add additional context in comments.

4 Comments

What does the zip method do?
Nathan_U, I anticipated your question :-) Let me know if that's not clear.
That makes sense, thanks! So, zip puts both values together to make a 2d array, and map changes the values to the sum with { |i,j| i+j }. What I'm trying to do is create a one-time pad program as I'm learning ruby. So my question was to enable me to XOR the message by the key. All I need to do now is learn how to turn the characters into binary and back again and I'll be 70% there!
Nathan_U, have a look at Fixnum#to_s(base) and String#to_i(base).
3

OPTION 1:

For a pure Ruby solution, try the transpose method:

a = [1,2,3,4]
b = [3,4,5,6]
c = [a, b].transpose.map{|x, y| x + y} 
#=> [4,6,8,10]

OPTION 2:

If you're in a Rails environment, you can utilize Rails' sum method:

[a, b].transpose.map{|x| x.sum} 
#=> [4,6,8,10]

EXPLANATION:

transpose works perfectly for your scenario, since it raises an IndexError if the sub-arrays don't have the same length. From the docs:

Assumes that self is an array of arrays and transposes the rows and columns. If the length of the subarrays don’t match, an IndexError is raised.

2 Comments

What exactly does the transpose method do?
I've updated the answer with an explanation of both the Ruby transpose method and the Rails sum method.

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.