Sorting arrays syntax in ruby
This is a very basic question but I'm having a bit of trouble understanding Rubys hash sort metho开发者_JS百科d.
Basically whats happening is I'm receiving a cannot convert string to integer so my first guess is I'm sorting the array by a string (which is actually a number). The array contains hashes and I'm trying to sort it by one of the hashes values that I've identified with a key.
Heres how I'm sorting my array:
@receivedArray =(params[:respElementDatas])
puts @receivedArray.class #Its definitely an array
@sortedArray = @receivedArray.sort_by{|ed| ed["element_type_id"]}
The error I'm getting is can't convert String into Integer on the sort line.
Naturally I assumed that
Just a quick question. Am i right in saying that 'ed' is an object that is stored in the array and I'm referencing it correctly? Also any pointers on how to fix it?
Your @receivedArray
is an array of arrays or has at least one array in it. For example:
a = [[1,2,3],[4,5,6]]
[[1, 2, 3], [4, 5, 6]]
a.sort_by { |e| e['x'] }
# TypeError: can't convert String into Integer
a = [{:a => :a},{:b => :b},[1,2,3]]
[{:a=>:a}, {:b=>:b}, [1, 2, 3]]
a.sort_by { |e| e['x'] }
# TypeError: can't convert String into Integer
a = [{'where' => 'is'},{'pancakes' => 'house'}]
[{"where"=>"is"}, {"pancakes"=>"house"}]
a.sort_by { |e| e['x'] }
# No error this time
try ed["element_type_id"].to_i
You are right in saying that 'ed' is an object that is stored in the array. If all the elements in the array are hashes then you are referencing it correctly?
Some of the hashes have a String and others have an Integer for the element_type_id.
I'd check where you are mixing the data for the element_type_id.
You could try ed["element_type_id"].to_i
which for an integer will have no effect, but for a string will parse it into an integer.
It looks like your error is saying that ed
is an Array
, not a Hash
. It may be an array of pairs: [['key1', 'value1'], ['key2', 'value2']]
, in which case you would want to change your code to:
@sortedArray = @receivedArray.sort_by{ |ed| ed.assoc("element_type_id") }
As rubyprince suggested, seeing the output of p @receivedArray
would help clarify this.
精彩评论