Question

I have a array i getting through an xml .i want to iterate every element to the array which is hash and get the every hash element value using key. I want to someting like this>>

array>>

education_split = [{"University"=>"Institute Of Engineering And Emerging Technologies", "Degree"=>"MBA", "Year"=>"2007"}, {"University"=>"H.N.B. Garhwal University", "Degree"=>"MSC", "Year"=>"2005"}, {"University"=>"H.P. University", "Degree"=>"Med", "Year"=>"2003"}, {"University"=>nil, "Degree"=>"12th", "Year"=>"1999"}, {"University"=>nil, "Degree"=>"10th", "Year"=>nil}] 

now i want to iterate to every element of the array and get the value of university ,degree,year in iteration. something like that..

 education_split.each do |edu|
     //here are some other things also like creating object
      edu["University"] 
      edu ["Degree"] 
      edu["Year"]
   end    

This is also working but in some cases it is though error >> TypeError (no implicit conversion of String into Integer)

here all fields are string and values i am getting are also string.

Was it helpful?

Solution

Just need to check a hash :

education_split.each do |edu|
     //here are some other things also like creating object
  if edu.is_a? Hash
      edu["University"] 
      edu ["Degree"] 
      edu["Year"]
  end
end  

Reading the error, I am sure your collection education_split contains also arrays with hashes. Now to prevent the error and as you interested only to hash that part of the code, just do a check if edu in any particular iteration, is a hash or not. if hash, do your operation or skip it.

TypeError (no implicit conversion of String into Integer) only comes, when you would try to get array elements using strings, instead of integers. Like a = [1, 2], and now do a['x'], and see you would get the exact error you are now getting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top