Florian Gross
3/19/2005 4:58:00 PM
Aquila wrote:
> Actually the code has less duplication, this was just an example. But why
> doesn't this work:
> def keyToName(key)
> case key.strip
> ...
> when "h" "Element handlers"
> when "a" "See also"
> else "Unknown key"
> end
> end
>
> puts keyToName("a")
> puts keyToName('a')
> It gives "Unknown key" twice, instead of "See also" at least once.
Hah, I knew that you weren't supposed to use when like that. You're
actually doing this with the above code:
case key.strip
when "hElement handlers"
when "aSee also"
else "Unknown key"
end
Which of course isn't what you want. Put a "then" or ":" between the
condition and the action parts and it will work.
>>Though I wonder if you're not better of with a Hash:
>>
>>puts({
>> "c" => "Synopsis",
>> "s" => "Category",
>> ...
>>}[key.strip])
>
> That sounds nice, is that code faster?
It ought to be faster, especially when you assign the Hash to a
constant, but I doubt that it will matter much.