Turning a case/when into a Hash (for a yaml file)

x = 4_924

case x
when 0…100
1
when 101…500
2
when 501…1_000
3
when 1_001…5_000
4
when 5_000…1_000_000
5
else
0
end

I would like to turn the above into:

(a) a hash instead
(b) store it into a yaml file.

This is actually a XP Table for Levels. Like, you reach level 3 when you
have at least 501 xp and at maxim 1000 xp.

On Fri, Jan 13, 2012 at 2:50 PM, Marc H. [email protected]
wrote:

4
when 5_000…1_000_000
5
else
0
end

I would like to turn the above into:

(a) a hash instead
(b) store it into a yaml file.

Each of the “when” conditions is a range object. The “else” condition
is obviously not. Range objects can be a key in a hash, so you can
have (untested)

{ 0…100 => 1, 101…500 => 2, …, :else => 0 }

and that Hash can be stored as YAML.

Then you need to write a method

def level_for_xp(hash, xp)

end

which is easily done.

Rather than a hash, I would go for an array of arrays:

[ [0…100, 1], [101…500, 2], …, [:else, 0] ]

Reason: preserve order. I know the current implementation of Ruby’s
hashes does preserve insertion order, but that’s an implementation
detail. For this usage, preserving order is a conceptual detail.

Gavin

Thanks, that answered it very well!