Topic: Problem with array of hashes

Hi ,

I have created an array of hashes using

Model file class

Class A < ActiveRecord::Base

def fill_paths
paths = Array.new
    for file in @files
      path = {}
      path["a"] = file
      path["b"] = DATA2(assume data2 is valid)
      paths << path
    end
return paths
end

in controller class

@paths = A.fill_paths
for path in @paths
      puts path.a
end

I cant access path.a, which says
"undefined method 'a'  for{"a"=>value1,"b"=>value2}:Hash
//value1, value2 are valid data

Please let me know whats wrong with this.
To add to this paths["a"] works, but i wanted to convert this hash into a class
How do i do that?

Last edited by cybercoder (2012-06-05 14:13:44)

Re: Problem with array of hashes

When calling

A.fill_paths

you are calling a class method, but your 'fill_paths' is an instance method and could be called only on an instance (object) of 'A' class.
The below code should work:

a = A.new
paths = a.fill_paths

Or you could change the method to be a class one like that:

class A < AR
  def self.fill_paths
     #your method body as before, just remove 'return' statement and leave paths variable at the very last line before end, Ruby returns it OOTB :).
  end
end

Now you will be able to call it as you did:

paths = A.fill_paths

Last edited by Javix (2012-06-05 15:22:11)