Jefferson Jefferson - 1 month ago 7
Ruby Question

addressable/uri gives params in alphabetical order in ruby

addressable/uri gives params in alphabetic order. If I want to get the query params as in the hash(i.e nonce, method, rate, order_type, quantity) how should I change my code?

2.1.0 :060 > require "addressable/uri"
2.1.0 :061 > uri = Addressable::URI.new
2.1.0 :062 > uri.query_values = Hash["nonce" => 1405069051840, "method" => "a", "rate" => "rate", "order_type" => "order_type", "quantity" => "quantity"]
=> {"nonce"=>1405069051840, "method"=>"a", "rate"=>"rate", "order_type"=>"order_type", "quantity"=>"quantity"}
2.1.0 :063 > params = uri.query
=> "method=a&nonce=1405069051840&order_type=order_type&quantity=quantity&rate=rate"


I need output like this:(as I passed)

"nonce=1405069051840&method=a&rate=rate&order_type=order_type&quantity=quantity"


Output now is (alphabetical order)

"method=a&nonce=1405069051840&order_type=order_type&quantity=quantity&rate=rate"

Answer

Pass in an Array of [key, value] pairs instead of a Hash if you want the Addressable gem to preserve the order of the paramaters.

uri.query_values = [ [ "nonce", 1405069051840 ], ["method", "a" ], ... ]