Indeed this is a nice solution to the problem of assigning a value.
However the 'temp == ...' was of my own invention and not part of the
OP. That simply gave 'condition1', 'condition2' etc so there is a strong
possibility that what you propose would not work for him as the
conditions might not be based upon the same variable as in my example,
if the OP is new to programming you will have led him down the wrong
path by not pointing out that your solution only works for conditions
based upon the conditions all being tests of temp.
Also when posting code it helps to run it, no matter how much of a
genius you are. Your code does not do what mine did. Try this instead:
x = case temp
when 'cat' then 1
when 'dog' then 2
when 'banana' then 3
else nil
end
I would worry less about how many keystrokes you have saved and spend a
little more time getting it right and testing your code. You wrote 3
lines less than me and got it completely backwards.
On a more general note, here are some guidelines I use to write clear
code. All of these guidelines follow the principle of lightening the
load on your working memory:
(1) Name variables what you call them. If you have a variable named
a and someone asks, "What's a?" and you say "That's the amount of time
left", then rename a to time_left.
(2) In general, avoid abbreviations. The time you save typing is
wasted in other areas. While it may be completely obvious to you that
"prev" means preview, the comment next to the code that mentions
"previous" values can confuse the issue (yes, this is a real-life
example). Abbreviations also may force the user of your code to have
to look up method names more often (Now was that method called prev or
previous?)
(3) Write cohesively. Ideally, each part of the system should be
responsible for one clearly-expressed thing. Each method should have
one purpose, each class should have one overarching, easily-expressed
purpose, etc.