9

I am trying to pair up two key value pairs but I am unsure how to accomplish this. Below is what I have attempted:

struc = Array[(3,4),(5,6)]
for i in 0..1
    puts "#{struc[i,i]}"
end

But my desired output is the following (which the previous code block does not produce):

3 4
5 6
0

3 Answers 3

23

Why not use a hash. With it, you can do:

struc = {3 => 4, 5 => 6}

To output the result, you can use the each_pair method, like so:

struc.each_pair do |key, value|
    puts "#{key} #{value}"
end
2
  • Watch out only works if first item is unique key: {3 => 4, 5 => 6, 3=> 5} will give: {3=>5, 5=>6} Jul 13, 2018 at 13:55
  • Its a hash, therefore the key will always be unique. Aug 7, 2018 at 5:44
11

try this:

arr = [[3,4],[5,6]]
arr.each do |(a,b)|
  puts "#{a} #{b}"
end

Also you array syntax (Array[(3,4),(5,6)]) is incorrect.

0
0

In Ruby 2.3 you can do the following:

arr = [[3,4],[5,6]]
arr.each do |a,b|
    puts "#{a} #{b}"
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.