Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash difference in 1.8.7 and 1.9.2

Tags:

ruby

Given the following script, I see a different output using Ruby 1.8.7 and Ruby 1.9.2. My question is, what has changed in Ruby hashes that enforces this particular behavior?

def to_params(_hash)
  params = ''
  stack = []

  _hash.each do |k, v|
    if v.is_a?(Hash)
      stack << [k,v]
    else
      #v = v.first if v.is_a?(Array)
      params << "#{k}=#{v}&"
    end
  end

  stack.each do |parent, hash|
    hash.each do |k, v|
      if v.is_a?(Hash)
        stack << ["#{parent}[#{k}]", v]
      else
        params << "#{parent}[#{k}]=#{v}&"
      end
    end
  end

  params.chop! # trailing &
  params
end

q = {"some_key"=>["some_val"], "another_key"=>["another_val"]}
n = convert_params(q)

puts n
  • Ruby 1.8.7 output:

some_key=some_val&another_key=another_val

  • Ruby 1.9.2 output:

some_key=["some_val"]&another_key=["another_val"]

1.9.2 retains the "Array" type of the value whereas 1.8.7 changes the type to string implicitly.

like image 901
randombits Avatar asked May 31 '11 13:05

randombits


1 Answers

Two things have changed (the latter being your observation):

  • Hashes are ordered now
  • array.to_s used to return array.join, now it returns array.inspect (see 1.8.7 and 1.9.2).
like image 52
Marcel Jackwerth Avatar answered Oct 19 '22 14:10

Marcel Jackwerth