0

I have this to work with:

[
  ["app1", {"name"=>"name1", "path"=>"xyz.com/"}],
  ["app2", {"name"=>"name2", "path"=>"xyz.com/"}],
  ["app3", {"name"=>"name3", "path"=>"xyz.com/"}],
  # etc.
]

I want to be able to access each name and path so I tried:

apps.each do |key, value|
  value.each do |key, value|
    puts value
  end
end

but this returns an Enumerator. Any idea how I can do this?

1
  • Consider creating your own Class for that kind of thing - more readable. Commented Mar 22, 2012 at 15:35

3 Answers 3

1
apps = [["app1", {"name"=>"name1", "path"=>"https://xyz.com/"}], ["app2", {"name"=>"name2", "path"=>"https:/xyz.com/"}], ["app3", {"name"=>"name3", "path"=>"https://xyz.com/"}]]
apps.flatten.each do |t|
  next unless t.class == Hash
  next unless t.key?("name")
  next unless t.key?("path")
  puts t.inspect # now t is a hash that has both "name" and "path" keys - do what you want
end

This will handle even a bit more complex cases when you have different structure for different elements.

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I ended up doing- apps = apps.flatten apps = apps.delete_if do |key, value| key.class == String end apps.each do |app| puts blah end
0

I think your first each loop is only looping over an array, so it would be:

apps.each do |app|
  app.each do |key, value|
    puts key   # would be app1 in the first array
    puts value["name"]
    puts value["path"]
  end
end

Comments

0
ar = [
  ["app1", {"name"=>"name1", "path"=>"xyz.com/"}],
  ["app2", {"name"=>"name2", "path"=>"xyz.com/"}],
  ["app3", {"name"=>"name3", "path"=>"xyz.com/"}]

]
#Get a specific app:
p ar.assoc("app2").last["name"]
#Get all names and paths
ar.each{|app|  name, path = app.last["name"], app.last["path"]}

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.