[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

access to the case/when variable

bwv549

1/3/2007 4:32:00 PM

Is there a way to access the variable being tossed through the
case/when structure?

case object.size.to_s
when /33/
# ...
when /44/
# ...
else
abort "Invalid variable: " + ???
# Is there a way to access the variable being tossed through
case/when?
# something like: $_, or $!
end

One can always do this:
x = object.size.to_s
case x
when /3ft/
when /4cm/
else
abort "Bad match: #{x}"
end

But it would save a line to be able to access the actual variable being
used in the case/when structure.

Thanks

2 Answers

Jeremy McAnally

1/3/2007 4:40:00 PM

0

case x = object.size.to_s
when /33/: # whatever
when /44/: #etc.
else
x = 999
# whatever
end

Basically a combination approach. :)

--Jeremy

On 1/3/07, bwv549 <jtprince@gmail.com> wrote:
> Is there a way to access the variable being tossed through the
> case/when structure?
>
> case object.size.to_s
> when /33/
> # ...
> when /44/
> # ...
> else
> abort "Invalid variable: " + ???
> # Is there a way to access the variable being tossed through
> case/when?
> # something like: $_, or $!
> end
>
> One can always do this:
> x = object.size.to_s
> case x
> when /3ft/
> when /4cm/
> else
> abort "Bad match: #{x}"
> end
>
> But it would save a line to be able to access the actual variable being
> used in the case/when structure.
>
> Thanks
>
>
>


--
My free Ruby e-book:
http://www.humblelittlerubybook...

My blogs:
http://www.mrneigh...
http://www.rubyinpra...

Robert Klemme

1/3/2007 4:48:00 PM

0

On 03.01.2007 17:32, bwv549 wrote:
> Is there a way to access the variable being tossed through the
> case/when structure?

You mean *object* not *variable*. But no.

> case object.size.to_s
> when /33/
> # ...
> when /44/
> # ...
> else
> abort "Invalid variable: " + ???
> # Is there a way to access the variable being tossed through
> case/when?
> # something like: $_, or $!
> end
>
> One can always do this:
> x = object.size.to_s
> case x
> when /3ft/
> when /4cm/
> else
> abort "Bad match: #{x}"
> end
>
> But it would save a line to be able to access the actual variable being
> used in the case/when structure.

If you want to save a line you can do

case x = object.size.to_s
....

Btw, why do you convert to string and then use regexps on the name? Do
you want to check for numbers with all the same digits? You can do that
with this RX: /^(\d)\1*$/

Kind regards

robert