I didn't know what kind of data was in this array. I only knew that the list would be in the following
value_array: {"Gamma"=>14, "Alpha"=>3, ..}And the list will be displayed to the user as:
Gamma(14)
Alpha(3)
..
But I want this list to be in alphabetical order so that 'Alpha' would appear before 'Gamma' and so on..
I tried using the ruby array sort method.
value_array = value_array.sort { |x,y| x[0] <=> y[0] }when I tried this on Scite ruby editor, it worked fine. But when tried on the app it failed with the error "comparison of Array with Array failed"
After about an hour of desperate struggle to find the solution, I stumbled upon this article: "Support for nil values in Enumerable.min or max"
ah.. the nil (or null if you like) object.. a common trouble creator. That is why we should always make sure are data is valid (not nil etc) i guess. So in my app, the huge list must have had some nil values. So I fixed it:
value_array = value_array.sort {|x,y| ( (y[0].nil? || x[0].nil?) ? 0 : (x[0] <=> y[0]) ) }
.. all part of the long journey of learning i guess :)
No comments :
Post a Comment