1

I'm trying to have an Array assign a value to two variables.

test = "hello, my,name,is,dog,how,are,you"
testsplit = test.split "," 
testsplit.each do |x,y|
  puts y
end

I would think that it would print

my
is
how
you

but it appears the values only get passed to x and not to y. When I run this code, y comes back empty.

1
  • 1
    Your title needs fixing. There is no hash and your reference to "multiple assignment" is unclear. Commented Oct 2, 2013 at 16:47

2 Answers 2

5

Array#each will pass only one item for each iteration(thus x will be assigned a value from the array for every pass,whereas y will always be assigned to nil).Thus you need to use Enumerable#each_slice method with argument as 2.

test = "hello, my,name,is,dog,how,are,you"
testsplit = test.split "," 

testsplit.each_slice(2) do |x,y|
  puts y
end

# >>  my
# >> is
# >> how
# >> you
Sign up to request clarification or add additional context in comments.

Comments

4

You can use each_slice to take 2 elements at a time:

test = "hello, my,name,is,dog,how,are,you"
testsplit = test.split "," 

testsplit.each_slice(2) do |x,y|
  puts y
end

# =>  my, is, how, you

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.