Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

ruby - Shortcut to make case/switch return a value

I'm pretty sure I saw someone do a shortcut technique like the code below (which doesn't work)

return case guess
  when guess > @answer then :high
  when guess < @answer then :low
  else :correct
end

Does anyone know the trick I'm referring to?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A case statement does return a value, you just have to use the right form of it to get the value you're expecting.

There are two forms of case in Ruby. The first one looks like this:

case expr
when expr1 then ...
when expr2 then ...
else ...
end

This will compare expr with each when expression using === (that's a triple BTW) and it will execute the first then where === gives a true value. For example:

case obj
when Array then do_array_things_to(obj)
when Hash  then do_hash_things_to(obj)
else raise 'nonsense!'
end

is the same as:

if(Array === obj)
  do_array_things_to(obj)
elsif(Hash === obj)
  do_hash_things_to(obj)
else
  raise 'nonsense!'
end

The other form of case is just a bunch of boolean conditions:

case
when expr1 then ...
when expr2 then ...
else ...
end

For example:

case
when guess > @answer then :high
when guess < @answer then :low
else :correct
end

is the same as:

if(guess > @answer)
  :high
elsif(guess < @answer)
  :low
else
  :correct
end

You're using the first form when you think you're using the second form so you end up doing strange (but syntactically valid) things like:

(guess > @answer) === guess
(guess < @answer) === guess

In either case, case is an expression and returns whatever the matched branch returns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...