Ruby Case Statement || Ruby Switch Statement

Ruby is awesome but sometimes it throws me a curve ball.

x = 'bar'

case x
when 'foo' || 'bar'
  puts x
end

At first glance I expected this to output ‘bar’, but instead nothing!
Looking at the if statement equivalent, it becomes clear.

x = 'bar'

if x == ('foo' || 'bar')
  puts x
end

The “||” operator is evaluated before the comparison is made. Here’s the correct case statement format to get a ‘bar’:

x = 'bar'

case x
when 'foo', 'bar'
  puts x
end

# => bar
Advertisements
Posted in ruby

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

%d bloggers like this: