access to the case/when variable

B

bwv549

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
 
J

Jeremy McAnally

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

Basically a combination approach. :)

--Jeremy

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.com/book/

My blogs:
http://www.mrneighborly.com/
http://www.rubyinpractice.com/
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,222
Messages
2,571,137
Members
47,754
Latest member
Armand37T7

Latest Threads

Top