0

I have:

Array1 = [x, y, z]
Array2 = [m, n]
a = b

hash1 = {Array1 => val1,
         Array2 => val2,
         a => c
        }

How to iterate inside each element of Array1, Array2 inside the hash1?

hash1.each do |t|
  t[0] #gives me Array1 as a string. I need [x,y,z]

end 
3
  • 2
    from where c come ? what is a=b? Commented May 31, 2014 at 20:30
  • 1
    Please answer Arup's question by editing your question, rather than trying to explain in a comment. Commented May 31, 2014 at 20:41
  • 1
    From a style perspective, variables in Ruby should be lower_case only. Classes are MixedCase, and constants are ALL_CAPS. Declaring variables as if they were classes is confusing. Commented May 31, 2014 at 22:53

2 Answers 2

1

It don't give you a string. It give you the correct array.

{
  [1,2] => 'a'
}.each{|t| puts t[0].class}
# prints array
{
  [1,2] => 'a'
}.each{|t| puts t[0][0]}
# prints 1

Note that you are doing each on a hash. You can deconstruct the key-value pair giving two variables to the block, like this:

{a:1, b:2}.each { |k,v| p k; p v }
#prints :a
#prints 1
#prints :b
#prints 2
Sign up to request clarification or add additional context in comments.

Comments

0

Something like this

hash1.keys.each do |k|
  if k.is_a?(Array)
    k.each do |v|
      .. Do something here ..
    end
  end
end

Just replace the Do something here with the code you want, and v will be the value in the array

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.