0

How can I access the three objects in this hash separately?

hash = {"Paul" => [25, 18]}

In this code,

hash.each_pair do |k, v|
  print "#{k}: "
  v.each do |n|
    print "#{n} "
  end
  print "\n"
end

the variable n accesses [25, 18] as a single object. Doing for example |n, m| does not work.

2 Answers 2

1

You could something like below

hash = {}
hash["Paul"] = [25, 18]

hash.each_pair do |k, (v1, v2, *rest)|
    print "#{k}: "
    print "#{v1} "
    print "#{v2} "
    print "\n"
end
#=> Paul: 25 18 

Alternatively, you could try something like below:

hash = {}
hash["Paul"] = [25, 18]

hash.each_pair do |k, v|
    print "#{k}: "
    v.tap { |m, n| 
        print "#{m} "
        print "#{n} "
    }
    print "\n"
end
#=> Paul: 25 18 
Sign up to request clarification or add additional context in comments.

Comments

0
p [hash.keys, hash.values].flatten
  # ["Paul", 25, 18]

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.