elsif and case in Ruby

Practical guidence:
fruit = “orange”
if fruit == “orange”
color = “orange”
elsif fruit == “apple”
color = “green”
elsif fruit == “banana”
color = “yellow”
else
color = “unknown”
end

puts color

output:

orange

A variant of this technique is to use a case block. Our preceding example, with a case
block, becomes the following:
fruit = “orange”
case fruit
when “orange”
color = “orange”
when “apple”
color = “green”
when “banana”
color = “yellow”
else
color = “unknown”
end
output:

orange

case has another trick up its sleeve. As all Ruby expressions return a result, you can
make the previous example even shorter:

fruit = “orange”
color = case fruit
when “orange”
“orange”
when “apple”
“green”
when “banana”
“yellow”
else
“unknown”
end

output:

orange

Regards,

P.Raveendran

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s