On 5/6/2011 08:50, Brad S. wrote:
SO BE CAREFUL WHEN USING “id”
Actually, be careful using hashes (which is what you’re implicitly
doing) if you care about key ordering. The arguments you’re passing to
the programme method are converted into a Hash object by Ruby prior to
being passed. In the Ruby 1.8 series and earlier, the order of the hash
keys is not preserved, so your keys may come out in any order when
they’re enumerated. See what happens if you do this:
ids.each do |num|
xml.programme(:alpha => alphas.fetch(ids.index(num)), :num => num)
Most likely you’ll end up with the num attribute followed by the alpha
attribute just like your last example even though the order of them is
switched in my example. If that’s not the case, let us know, but you’ll
probably have to take a look at the source for builder in order to
figure out why.
It’s possible that you’ll get what you want if you switch to Ruby 1.9.2.
The Ruby 1.9 series preserves the order of hash keys based on insertion
order. You may also be able to do what you want in Ruby 1.8 by either
wrapping or extending Hash to make your own Hash-like object that
preserves key order.
This thread may be helpful for you. It even includes a potential
implementation for an order preserving Hash if you’re interested:
Here’s a gem for such an implementation:
Using that will make your code a little ugly, but it may be worth it if
you’re really concerned about the order of the attributes in your XML.