Jean Jean - 1 year ago 116
Perl Question

Ruby multiple statements on single line with condition

What is the cleanest way to write following code in Ruby?

if ($string eq "dasff1") { print "dasff1" ;print " hoiff1" }
elsif ($string eq "dasff2") { print "dasff2" ;print " hoiff2" }
elsif ($string eq "dasff3") { print "dasff3" ;print " hoiff3" }

i.e multiple statements on a single line qualified with a condition.

Is there an alternate way other than

if (string == "dasff1")
print "dasff1" ;print " hoiff1"
elsif (string == "dasff2")
print "dasff2" ;print " hoiff2"
elsif (string == "dasff3")
print "dasff3" ;print " hoiff3"

Answer Source

You could use :

string = "dasff1"

case string
when "dasff1" then print "dasff1"; print " hoiff1"
when "dasff2" then print "dasff2"; print " hoiff2"
when "dasff3" then print "dasff3"; print " hoiff3"

Or just :

print string+" "+string.sub('das','hoi') if string=~/^dasff[1-3]$/

You shouldn't do that, but since you asked for it :

if    (string == "dasff1"); print "dasff1" ; print " hoiff1"
elsif (string == "dasff2"); print "dasff2" ; print " hoiff2"
elsif (string == "dasff3"); print "dasff3" ; print " hoiff3"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download