On Thu, Jul 14, 2011 at 10:56 AM, I=F1aki Baz Castillo <ibc / aliax.net> wrot=
e:
> Hi, the following code does not "compile":
>
> -----------------------------
> =A0def test1
> =A0 =A0value =3D return("lalala")
> =A0end
> -----------------------------
> =3D> SyntaxError: (irb):11: void value expression
>
>
> Ok, it makes sense. So then, why the following does not fail?
>
> -----------------------------
> =A0def test2
> =A0 =A0value =3D case 123
> =A0 =A0 =A0when Fixnum
> =A0 =A0 =A0 =A0return "returning 'Fixnum' string from method test2"
> =A0 =A0 =A0end
> =A0 =A0puts "method test2 ends now"
> =A0end
> --------------------------
> irb> test2
> =3D> "returning 'Fixnum' string from method kk"

Probably because case has branches which actually return a value (even
if it is fall through and nil).  Interestingly enough this does not
work with if:

11:07:59 ~$ ruby19 -c x.rb
x.rb:7: void value expression
11:08:04 ~$ cat -n x.rb
     1
     2  def a
     3    x =3D if rand(10) =3D=3D 0
     4      99
     5      else
     6      return 55
     7      end
     8  end
11:08:07 ~$

Could be that you have found a loophole in the parser logic. :-)

> I'm using Ruby 1.9.2 and in fact I use a method like "test2" it in my
> project, but it seems a bit strange for me and I would like to be sure
> that it's something correct (even if IMHO it does not make sense) and
> will not change in a future Ruby 1.9 version.

I'd say stop using this idiom.  If you use a "case" expression because
it should yield a value (i.e. "x =3D case...end") then I would only use
exceptions as other way out.  A "return" indicates regular execution
flow which in the case of this usage of "case" would mean "have case
return a value" but not "return from the method".

If you use "case" as a control flow construct (i.e. without assigning
the result) then a "return" inside is OK and Ruby will also accept it.
 Same goes for "if".

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/