ruby Array key pair value?

26,071

Solution 1

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.

Solution 2

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
Share:
26,071
RajG
Author by

RajG

Backend Developer - Ruby on Rails - London, UK

Updated on July 28, 2022

Comments

  • RajG
    RajG almost 2 years

    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
    
  • Ronan Fauglas
    Ronan Fauglas almost 6 years
    Watch out only works if first item is unique key: {3 => 4, 5 => 6, 3=> 5} will give: {3=>5, 5=>6}
  • Sunil Kumar
    Sunil Kumar over 5 years
    Its a hash, therefore the key will always be unique.